Compare commits

...
Author SHA1 Message Date
Matej Bačo e8380e592c WIP: Debug SQL connections 2023-10-06 12:50:21 +02:00
Matej Bačo 20dc84ee40 More find and replace for framework V2 2023-10-05 11:19:23 +02:00
Matej Bačo e82bad947a Namespace renaming for framework v2 2023-10-04 14:57:09 +02:00
Matej Bačo 1b4b8f17b3 Upgrade framework 2023-10-04 10:04:51 +02:00
Matej Bačo 47208ea1b3 Merge branch '1.4.x' into feat-framework-v2-new 2023-10-04 09:45:25 +02:00
Damodar Lohani 09d416eaa0 fix http 2023-09-25 02:34:59 +00:00
Damodar Lohani 4ddd4dadd9 update to app to Http 2023-09-10 12:30:32 +00:00
Damodar Lohani d691601115 composer update 2023-09-10 12:26:09 +00:00
87 changed files with 2293 additions and 1912 deletions
+3 -3
View File
@@ -8,7 +8,7 @@ use Appwrite\Platform\Appwrite;
use Utopia\CLI\CLI;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Service;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Cache\Adapter\Sharding;
use Utopia\Cache\Cache;
@@ -149,7 +149,7 @@ CLI::setResource('logError', function (Registry $register) {
$logger = $register->get('logger');
if ($logger) {
$version = App::getEnv('_APP_VERSION', 'UNKNOWN');
$version = Http::getEnv('_APP_VERSION', 'UNKNOWN');
$log = new Log();
$log->setNamespace($namespace);
@@ -168,7 +168,7 @@ CLI::setResource('logError', function (Registry $register) {
$log->setAction($action);
$isProduction = App::getEnv('_APP_ENV', 'development') === 'production';
$isProduction = Http::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
$responseCode = $logger->addLog($log);
+2 -2
View File
@@ -4,12 +4,12 @@
* List of Appwrite Cloud Functions supported runtimes
*/
use Utopia\App;
use Utopia\Http\Http;
use Appwrite\Runtimes\Runtimes;
$runtimes = new Runtimes('v2');
$allowList = empty(App::getEnv('_APP_FUNCTIONS_RUNTIMES')) ? [] : \explode(',', App::getEnv('_APP_FUNCTIONS_RUNTIMES'));
$allowList = empty(Http::getEnv('_APP_FUNCTIONS_RUNTIMES')) ? [] : \explode(',', Http::getEnv('_APP_FUNCTIONS_RUNTIMES'));
$runtimes = $runtimes->getAll(true, $allowList);
+2 -2
View File
@@ -4,12 +4,12 @@
* List of Appwrite Cloud Functions supported runtimes
*/
use Utopia\App;
use Utopia\Http\Http;
use Appwrite\Runtimes\Runtimes;
$runtimes = new Runtimes('v3');
$allowList = empty(App::getEnv('_APP_FUNCTIONS_RUNTIMES')) ? [] : \explode(',', App::getEnv('_APP_FUNCTIONS_RUNTIMES'));
$allowList = empty(Http::getEnv('_APP_FUNCTIONS_RUNTIMES')) ? [] : \explode(',', Http::getEnv('_APP_FUNCTIONS_RUNTIMES'));
$runtimes = $runtimes->getAll(true, $allowList);
+55 -55
View File
@@ -11,8 +11,8 @@ use Appwrite\Event\Mail;
use Appwrite\Event\Phone as EventPhone;
use Appwrite\Extend\Exception;
use Appwrite\Network\Validator\Email;
use Utopia\Validator\Host;
use Utopia\Validator\URL;
use Utopia\Http\Validator\Host;
use Utopia\Http\Validator\URL;
use Appwrite\OpenSSL\OpenSSL;
use Appwrite\Template\Template;
use Appwrite\URL\URL as URLParser;
@@ -24,7 +24,7 @@ use Utopia\Database\Validator\Query\Offset;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use MaxMind\Db\Reader;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Audit\Audit as EventAudit;
use Utopia\Config\Config;
use Utopia\Database\Database;
@@ -38,10 +38,10 @@ use Utopia\Database\Helpers\Role;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Locale\Locale;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Assoc;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Assoc;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\WhiteList;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PersonalData;
@@ -49,7 +49,7 @@ use Appwrite\Auth\Validator\PersonalData;
$oauthDefaultSuccess = '/auth/oauth2/success';
$oauthDefaultFailure = '/auth/oauth2/failure';
App::post('/v1/account')
Http::post('/v1/account')
->desc('Create account')
->groups(['api', 'account', 'auth'])
->label('event', 'users.[userId].create')
@@ -163,7 +163,7 @@ App::post('/v1/account')
->dynamic($user, Response::MODEL_ACCOUNT);
});
App::post('/v1/account/sessions/email')
Http::post('/v1/account/sessions/email')
->alias('/v1/account/sessions')
->desc('Create email session')
->groups(['api', 'account', 'auth', 'session'])
@@ -284,7 +284,7 @@ App::post('/v1/account/sessions/email')
$response->dynamic($session, Response::MODEL_SESSION);
});
App::get('/v1/account/sessions/oauth2/:provider')
Http::get('/v1/account/sessions/oauth2/:provider')
->desc('Create OAuth2 session')
->groups(['api', 'account'])
->label('error', __DIR__ . '/../../views/general/error.phtml')
@@ -320,7 +320,7 @@ App::get('/v1/account/sessions/oauth2/:provider')
$appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}';
if (!empty($appSecret) && isset($appSecret['version'])) {
$key = App::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']);
$key = Http::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']);
$appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \hex2bin($appSecret['iv']), \hex2bin($appSecret['tag']));
}
@@ -350,7 +350,7 @@ App::get('/v1/account/sessions/oauth2/:provider')
->redirect($oauth2->getLoginURL());
});
App::get('/v1/account/sessions/oauth2/callback/:provider/:projectId')
Http::get('/v1/account/sessions/oauth2/callback/:provider/:projectId')
->desc('OAuth2 callback')
->groups(['account'])
->label('error', __DIR__ . '/../../views/general/error.phtml')
@@ -382,7 +382,7 @@ App::get('/v1/account/sessions/oauth2/callback/:provider/:projectId')
]));
});
App::post('/v1/account/sessions/oauth2/callback/:provider/:projectId')
Http::post('/v1/account/sessions/oauth2/callback/:provider/:projectId')
->desc('OAuth2 callback')
->groups(['account'])
->label('error', __DIR__ . '/../../views/general/error.phtml')
@@ -415,7 +415,7 @@ App::post('/v1/account/sessions/oauth2/callback/:provider/:projectId')
]));
});
App::get('/v1/account/sessions/oauth2/:provider/redirect')
Http::get('/v1/account/sessions/oauth2/:provider/redirect')
->desc('OAuth2 redirect')
->groups(['api', 'account', 'session'])
->label('error', __DIR__ . '/../../views/general/error.phtml')
@@ -517,7 +517,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
}
if (!empty($appSecret) && isset($appSecret['version'])) {
$key = App::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']);
$key = Http::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']);
$appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \hex2bin($appSecret['iv']), \hex2bin($appSecret['tag']));
}
@@ -789,7 +789,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
;
});
App::get('/v1/account/identities')
Http::get('/v1/account/identities')
->desc('List Identities')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -840,7 +840,7 @@ App::get('/v1/account/identities')
]), Response::MODEL_IDENTITY_LIST);
});
App::delete('/v1/account/identities/:identityId')
Http::delete('/v1/account/identities/:identityId')
->desc('Delete Identity')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -871,7 +871,7 @@ App::delete('/v1/account/identities/:identityId')
return $response->noContent();
});
App::post('/v1/account/sessions/magic-url')
Http::post('/v1/account/sessions/magic-url')
->desc('Create magic URL session')
->groups(['api', 'account'])
->label('scope', 'public')
@@ -901,7 +901,7 @@ App::post('/v1/account/sessions/magic-url')
->inject('mails')
->action(function (string $userId, string $email, string $url, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Locale $locale, Event $events, Mail $mails) {
if (empty(App::getEnv('_APP_SMTP_HOST'))) {
if (empty(Http::getEnv('_APP_SMTP_HOST'))) {
throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP disabled');
}
@@ -1005,8 +1005,8 @@ App::post('/v1/account/sessions/magic-url')
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
$senderEmail = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$senderEmail = Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = Http::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$replyTo = "";
if ($smtpEnabled) {
@@ -1089,7 +1089,7 @@ App::post('/v1/account/sessions/magic-url')
;
});
App::put('/v1/account/sessions/magic-url')
Http::put('/v1/account/sessions/magic-url')
->desc('Create magic URL session (confirmation)')
->groups(['api', 'account', 'session'])
->label('scope', 'public')
@@ -1211,7 +1211,7 @@ App::put('/v1/account/sessions/magic-url')
$response->dynamic($session, Response::MODEL_SESSION);
});
App::post('/v1/account/sessions/phone')
Http::post('/v1/account/sessions/phone')
->desc('Create phone session')
->groups(['api', 'account'])
->label('scope', 'public')
@@ -1240,7 +1240,7 @@ App::post('/v1/account/sessions/phone')
->inject('locale')
->action(function (string $userId, string $phone, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Event $events, EventPhone $messaging, Locale $locale) {
if (empty(App::getEnv('_APP_SMS_PROVIDER'))) {
if (empty(Http::getEnv('_APP_SMS_PROVIDER'))) {
throw new Exception(Exception::GENERAL_PHONE_DISABLED, 'Phone provider not configured');
}
@@ -1347,7 +1347,7 @@ App::post('/v1/account/sessions/phone')
;
});
App::put('/v1/account/sessions/phone')
Http::put('/v1/account/sessions/phone')
->desc('Create phone session (confirmation)')
->groups(['api', 'account', 'session'])
->label('scope', 'public')
@@ -1463,7 +1463,7 @@ App::put('/v1/account/sessions/phone')
$response->dynamic($session, Response::MODEL_SESSION);
});
App::post('/v1/account/sessions/anonymous')
Http::post('/v1/account/sessions/anonymous')
->desc('Create anonymous session')
->groups(['api', 'account', 'auth', 'session'])
->label('event', 'users.[userId].sessions.[sessionId].create')
@@ -1600,7 +1600,7 @@ App::post('/v1/account/sessions/anonymous')
$response->dynamic($session, Response::MODEL_SESSION);
});
App::post('/v1/account/jwt')
Http::post('/v1/account/jwt')
->desc('Create JWT')
->groups(['api', 'account', 'auth'])
->label('scope', 'account')
@@ -1633,7 +1633,7 @@ App::post('/v1/account/jwt')
throw new Exception(Exception::USER_SESSION_NOT_FOUND);
}
$jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.
$jwt = new JWT(Http::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.
$response
->setStatusCode(Response::STATUS_CODE_CREATED)
@@ -1647,7 +1647,7 @@ App::post('/v1/account/jwt')
])]), Response::MODEL_JWT);
});
App::get('/v1/account')
Http::get('/v1/account')
->desc('Get account')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -1668,7 +1668,7 @@ App::get('/v1/account')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::get('/v1/account/prefs')
Http::get('/v1/account/prefs')
->desc('Get account preferences')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -1691,7 +1691,7 @@ App::get('/v1/account/prefs')
$response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES);
});
App::get('/v1/account/sessions')
Http::get('/v1/account/sessions')
->desc('List sessions')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -1730,7 +1730,7 @@ App::get('/v1/account/sessions')
]), Response::MODEL_SESSION_LIST);
});
App::get('/v1/account/logs')
Http::get('/v1/account/logs')
->desc('List logs')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -1791,7 +1791,7 @@ App::get('/v1/account/logs')
]), Response::MODEL_LOG_LIST);
});
App::get('/v1/account/sessions/:sessionId')
Http::get('/v1/account/sessions/:sessionId')
->desc('Get session')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -1836,7 +1836,7 @@ App::get('/v1/account/sessions/:sessionId')
throw new Exception(Exception::USER_SESSION_NOT_FOUND);
});
App::patch('/v1/account/name')
Http::patch('/v1/account/name')
->desc('Update name')
->groups(['api', 'account'])
->label('event', 'users.[userId].update.name')
@@ -1870,7 +1870,7 @@ App::patch('/v1/account/name')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::patch('/v1/account/password')
Http::patch('/v1/account/password')
->desc('Update password')
->groups(['api', 'account'])
->label('event', 'users.[userId].update.password')
@@ -1937,7 +1937,7 @@ App::patch('/v1/account/password')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::patch('/v1/account/email')
Http::patch('/v1/account/email')
->desc('Update email')
->groups(['api', 'account'])
->label('event', 'users.[userId].update.email')
@@ -2007,7 +2007,7 @@ App::patch('/v1/account/email')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::patch('/v1/account/phone')
Http::patch('/v1/account/phone')
->desc('Update phone')
->groups(['api', 'account'])
->label('event', 'users.[userId].update.phone')
@@ -2066,7 +2066,7 @@ App::patch('/v1/account/phone')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::patch('/v1/account/prefs')
Http::patch('/v1/account/prefs')
->desc('Update preferences')
->groups(['api', 'account'])
->label('event', 'users.[userId].update.prefs')
@@ -2100,7 +2100,7 @@ App::patch('/v1/account/prefs')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::patch('/v1/account/status')
Http::patch('/v1/account/status')
->desc('Update status')
->groups(['api', 'account'])
->label('event', 'users.[userId].update.status')
@@ -2144,7 +2144,7 @@ App::patch('/v1/account/status')
$response->dynamic($user, Response::MODEL_ACCOUNT);
});
App::delete('/v1/account/sessions/:sessionId')
Http::delete('/v1/account/sessions/:sessionId')
->desc('Delete session')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -2220,7 +2220,7 @@ App::delete('/v1/account/sessions/:sessionId')
throw new Exception(Exception::USER_SESSION_NOT_FOUND);
});
App::patch('/v1/account/sessions/:sessionId')
Http::patch('/v1/account/sessions/:sessionId')
->desc('Update OAuth session (refresh tokens)')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -2306,7 +2306,7 @@ App::patch('/v1/account/sessions/:sessionId')
throw new Exception(Exception::USER_SESSION_NOT_FOUND);
});
App::delete('/v1/account/sessions')
Http::delete('/v1/account/sessions')
->desc('Delete sessions')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -2367,7 +2367,7 @@ App::delete('/v1/account/sessions')
$response->noContent();
});
App::post('/v1/account/recovery')
Http::post('/v1/account/recovery')
->desc('Create password recovery')
->groups(['api', 'account'])
->label('scope', 'public')
@@ -2397,7 +2397,7 @@ App::post('/v1/account/recovery')
->inject('events')
->action(function (string $email, string $url, Request $request, Response $response, Document $user, Database $dbForProject, Document $project, Locale $locale, Mail $mails, Event $events) {
if (empty(App::getEnv('_APP_SMTP_HOST'))) {
if (empty(Http::getEnv('_APP_SMTP_HOST'))) {
throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP Disabled');
}
@@ -2462,8 +2462,8 @@ App::post('/v1/account/recovery')
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
$senderEmail = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$senderEmail = Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = Http::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$replyTo = "";
if ($smtpEnabled) {
@@ -2550,7 +2550,7 @@ App::post('/v1/account/recovery')
->dynamic($recovery, Response::MODEL_TOKEN);
});
App::put('/v1/account/recovery')
Http::put('/v1/account/recovery')
->desc('Create password recovery (confirmation)')
->groups(['api', 'account'])
->label('scope', 'public')
@@ -2638,7 +2638,7 @@ App::put('/v1/account/recovery')
$response->dynamic($recoveryDocument, Response::MODEL_TOKEN);
});
App::post('/v1/account/verification')
Http::post('/v1/account/verification')
->desc('Create email verification')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -2666,7 +2666,7 @@ App::post('/v1/account/verification')
->inject('mails')
->action(function (string $url, Request $request, Response $response, Document $project, Document $user, Database $dbForProject, Locale $locale, Event $events, Mail $mails) {
if (empty(App::getEnv('_APP_SMTP_HOST'))) {
if (empty(Http::getEnv('_APP_SMTP_HOST'))) {
throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP Disabled');
}
@@ -2714,8 +2714,8 @@ App::post('/v1/account/verification')
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
$senderEmail = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$senderEmail = Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = Http::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$replyTo = "";
if ($smtpEnabled) {
@@ -2799,7 +2799,7 @@ App::post('/v1/account/verification')
->dynamic($verification, Response::MODEL_TOKEN);
});
App::put('/v1/account/verification')
Http::put('/v1/account/verification')
->desc('Create email verification (confirmation)')
->groups(['api', 'account'])
->label('scope', 'public')
@@ -2860,7 +2860,7 @@ App::put('/v1/account/verification')
$response->dynamic($verificationDocument, Response::MODEL_TOKEN);
});
App::post('/v1/account/verification/phone')
Http::post('/v1/account/verification/phone')
->desc('Create phone verification')
->groups(['api', 'account'])
->label('scope', 'account')
@@ -2887,7 +2887,7 @@ App::post('/v1/account/verification/phone')
->inject('locale')
->action(function (Request $request, Response $response, Document $user, Database $dbForProject, Event $events, EventPhone $messaging, Document $project, Locale $locale) {
if (empty(App::getEnv('_APP_SMS_PROVIDER'))) {
if (empty(Http::getEnv('_APP_SMS_PROVIDER'))) {
throw new Exception(Exception::GENERAL_PHONE_DISABLED);
}
@@ -2956,7 +2956,7 @@ App::post('/v1/account/verification/phone')
->dynamic($verification, Response::MODEL_TOKEN);
});
App::put('/v1/account/verification/phone')
Http::put('/v1/account/verification/phone')
->desc('Create phone verification (confirmation)')
->groups(['api', 'account'])
->label('scope', 'public')
+21 -21
View File
@@ -3,7 +3,7 @@
use Appwrite\Extend\Exception;
use Appwrite\URL\URL as URLParse;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Database;
@@ -15,12 +15,12 @@ use Utopia\Domains\Domain;
use Utopia\Image\Image;
use Utopia\Logger\Log;
use Utopia\Logger\Logger;
use Utopia\Validator\Boolean;
use Utopia\Validator\HexColor;
use Utopia\Validator\Range;
use Utopia\Validator\Text;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\Boolean;
use Utopia\Http\Validator\HexColor;
use Utopia\Http\Validator\Range;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\URL;
use Utopia\Http\Validator\WhiteList;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
@@ -155,7 +155,7 @@ $getUserGitHub = function (string $userId, Document $project, Database $dbForPro
];
} catch (Exception $error) {
if ($logger) {
$version = App::getEnv('_APP_VERSION', 'UNKNOWN');
$version = Http::getEnv('_APP_VERSION', 'UNKNOWN');
$log = new Log();
$log->setNamespace('console');
@@ -174,7 +174,7 @@ $getUserGitHub = function (string $userId, Document $project, Database $dbForPro
$log->setAction('avatarsGetGitHub');
$isProduction = App::getEnv('_APP_ENV', 'development') === 'production';
$isProduction = Http::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
$responseCode = $logger->addLog($log);
@@ -190,7 +190,7 @@ $getUserGitHub = function (string $userId, Document $project, Database $dbForPro
return [];
};
App::get('/v1/avatars/credit-cards/:code')
Http::get('/v1/avatars/credit-cards/:code')
->desc('Get credit card icon')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -210,7 +210,7 @@ App::get('/v1/avatars/credit-cards/:code')
->inject('response')
->action(fn (string $code, int $width, int $height, int $quality, Response $response) => $avatarCallback('credit-cards', $code, $width, $height, $quality, $response));
App::get('/v1/avatars/browsers/:code')
Http::get('/v1/avatars/browsers/:code')
->desc('Get browser icon')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -230,7 +230,7 @@ App::get('/v1/avatars/browsers/:code')
->inject('response')
->action(fn (string $code, int $width, int $height, int $quality, Response $response) => $avatarCallback('browsers', $code, $width, $height, $quality, $response));
App::get('/v1/avatars/flags/:code')
Http::get('/v1/avatars/flags/:code')
->desc('Get country flag')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -250,7 +250,7 @@ App::get('/v1/avatars/flags/:code')
->inject('response')
->action(fn (string $code, int $width, int $height, int $quality, Response $response) => $avatarCallback('flags', $code, $width, $height, $quality, $response));
App::get('/v1/avatars/image')
Http::get('/v1/avatars/image')
->desc('Get image from URL')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -306,7 +306,7 @@ App::get('/v1/avatars/image')
unset($image);
});
App::get('/v1/avatars/favicon')
Http::get('/v1/avatars/favicon')
->desc('Get favicon')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -348,8 +348,8 @@ App::get('/v1/avatars/favicon')
CURLOPT_URL => $url,
CURLOPT_USERAGENT => \sprintf(
APP_USERAGENT,
App::getEnv('_APP_VERSION', 'UNKNOWN'),
App::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)
Http::getEnv('_APP_VERSION', 'UNKNOWN'),
Http::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)
),
]);
@@ -448,7 +448,7 @@ App::get('/v1/avatars/favicon')
unset($image);
});
App::get('/v1/avatars/qr')
Http::get('/v1/avatars/qr')
->desc('Get QR code')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -488,7 +488,7 @@ App::get('/v1/avatars/qr')
->send($image->output('png', 9));
});
App::get('/v1/avatars/initials')
Http::get('/v1/avatars/initials')
->desc('Get user initials')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -571,7 +571,7 @@ App::get('/v1/avatars/initials')
->file($image->getImageBlob());
});
App::get('/v1/cards/cloud')
Http::get('/v1/cards/cloud')
->desc('Get Front Of Cloud Card')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -778,7 +778,7 @@ App::get('/v1/cards/cloud')
->file($baseImage->getImageBlob());
});
App::get('/v1/cards/cloud-back')
Http::get('/v1/cards/cloud-back')
->desc('Get Back Of Cloud Card')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
@@ -856,7 +856,7 @@ App::get('/v1/cards/cloud-back')
->file($baseImage->getImageBlob());
});
App::get('/v1/cards/cloud-og')
Http::get('/v1/cards/cloud-og')
->desc('Get OG Image From Cloud Card')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
+19 -19
View File
@@ -2,11 +2,11 @@
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Document;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Text;
App::init()
Http::init()
->groups(['console'])
->inject('project')
->action(function (Document $project) {
@@ -16,7 +16,7 @@ App::init()
});
App::get('/v1/console/variables')
Http::get('/v1/console/variables')
->desc('Get variables')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -29,24 +29,24 @@ App::get('/v1/console/variables')
->label('sdk.response.model', Response::MODEL_CONSOLE_VARIABLES)
->inject('response')
->action(function (Response $response) {
$isDomainEnabled = !empty(App::getEnv('_APP_DOMAIN', ''))
&& !empty(App::getEnv('_APP_DOMAIN_TARGET', ''))
&& App::getEnv('_APP_DOMAIN', '') !== 'localhost'
&& App::getEnv('_APP_DOMAIN_TARGET', '') !== 'localhost';
$isDomainEnabled = !empty(Http::getEnv('_APP_DOMAIN', ''))
&& !empty(Http::getEnv('_APP_DOMAIN_TARGET', ''))
&& Http::getEnv('_APP_DOMAIN', '') !== 'localhost'
&& Http::getEnv('_APP_DOMAIN_TARGET', '') !== 'localhost';
$isVcsEnabled = !empty(App::getEnv('_APP_VCS_GITHUB_APP_NAME', ''))
&& !empty(App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY', ''))
&& !empty(App::getEnv('_APP_VCS_GITHUB_APP_ID', ''))
&& !empty(App::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''))
&& !empty(App::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''));
$isVcsEnabled = !empty(Http::getEnv('_APP_VCS_GITHUB_APP_NAME', ''))
&& !empty(Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY', ''))
&& !empty(Http::getEnv('_APP_VCS_GITHUB_APP_ID', ''))
&& !empty(Http::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''))
&& !empty(Http::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''));
$isAssistantEnabled = !empty(App::getEnv('_APP_ASSISTANT_OPENAI_API_KEY', ''));
$isAssistantEnabled = !empty(Http::getEnv('_APP_ASSISTANT_OPENAI_API_KEY', ''));
$variables = new Document([
'_APP_DOMAIN_TARGET' => App::getEnv('_APP_DOMAIN_TARGET'),
'_APP_STORAGE_LIMIT' => +App::getEnv('_APP_STORAGE_LIMIT'),
'_APP_FUNCTIONS_SIZE_LIMIT' => +App::getEnv('_APP_FUNCTIONS_SIZE_LIMIT'),
'_APP_USAGE_STATS' => App::getEnv('_APP_USAGE_STATS'),
'_APP_DOMAIN_TARGET' => Http::getEnv('_APP_DOMAIN_TARGET'),
'_APP_STORAGE_LIMIT' => +Http::getEnv('_APP_STORAGE_LIMIT'),
'_APP_FUNCTIONS_SIZE_LIMIT' => +Http::getEnv('_APP_FUNCTIONS_SIZE_LIMIT'),
'_APP_USAGE_STATS' => Http::getEnv('_APP_USAGE_STATS'),
'_APP_VCS_ENABLED' => $isVcsEnabled,
'_APP_DOMAIN_ENABLED' => $isDomainEnabled,
'_APP_ASSISTANT_ENABLED' => $isAssistantEnabled
@@ -55,7 +55,7 @@ App::get('/v1/console/variables')
$response->dynamic($variables, Response::MODEL_CONSOLE_VARIABLES);
});
App::post('/v1/console/assistant')
Http::post('/v1/console/assistant')
->desc('Ask Query')
->groups(['api', 'assistant'])
->label('scope', 'assistant.read')
+63 -63
View File
@@ -14,7 +14,7 @@ use Appwrite\Utopia\Database\Validator\Queries\Databases;
use Appwrite\Utopia\Database\Validator\Queries\Indexes;
use Appwrite\Utopia\Response;
use MaxMind\Db\Reader;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Audit\Audit;
use Utopia\Config\Config;
use Utopia\Database\Adapter\MariaDB;
@@ -44,17 +44,17 @@ use Utopia\Database\Validator\Query\Offset;
use Utopia\Database\Validator\Structure;
use Utopia\Database\Validator\UID;
use Utopia\Locale\Locale;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Boolean;
use Utopia\Validator\FloatValidator;
use Utopia\Validator\IP;
use Utopia\Validator\Integer;
use Utopia\Validator\JSON;
use Utopia\Validator\Nullable;
use Utopia\Validator\Range;
use Utopia\Validator\Text;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Boolean;
use Utopia\Http\Validator\FloatValidator;
use Utopia\Http\Validator\IP;
use Utopia\Http\Validator\Integer;
use Utopia\Http\Validator\JSON;
use Utopia\Http\Validator\Nullable;
use Utopia\Http\Validator\Range;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\URL;
use Utopia\Http\Validator\WhiteList;
/**
* Create attribute of varying type
@@ -370,7 +370,7 @@ function updateAttribute(
return $attribute;
}
App::post('/v1/databases')
Http::post('/v1/databases')
->desc('Create database')
->groups(['api', 'database'])
->label('event', 'databases.[databaseId].create')
@@ -447,7 +447,7 @@ App::post('/v1/databases')
->dynamic($database, Response::MODEL_DATABASE);
});
App::get('/v1/databases')
Http::get('/v1/databases')
->desc('List databases')
->groups(['api', 'database'])
->label('scope', 'databases.read')
@@ -495,7 +495,7 @@ App::get('/v1/databases')
]), Response::MODEL_DATABASE_LIST);
});
App::get('/v1/databases/:databaseId')
Http::get('/v1/databases/:databaseId')
->desc('Get database')
->groups(['api', 'database'])
->label('scope', 'databases.read')
@@ -521,7 +521,7 @@ App::get('/v1/databases/:databaseId')
$response->dynamic($database, Response::MODEL_DATABASE);
});
App::get('/v1/databases/:databaseId/logs')
Http::get('/v1/databases/:databaseId/logs')
->desc('List database logs')
->groups(['api', 'database'])
->label('scope', 'databases.read')
@@ -607,7 +607,7 @@ App::get('/v1/databases/:databaseId/logs')
});
App::put('/v1/databases/:databaseId')
Http::put('/v1/databases/:databaseId')
->desc('Update database')
->groups(['api', 'database', 'schema'])
->label('scope', 'databases.write')
@@ -652,7 +652,7 @@ App::put('/v1/databases/:databaseId')
$response->dynamic($database, Response::MODEL_DATABASE);
});
App::delete('/v1/databases/:databaseId')
Http::delete('/v1/databases/:databaseId')
->desc('Delete database')
->groups(['api', 'database', 'schema'])
->label('scope', 'databases.write')
@@ -697,7 +697,7 @@ App::delete('/v1/databases/:databaseId')
$response->noContent();
});
App::post('/v1/databases/:databaseId/collections')
Http::post('/v1/databases/:databaseId/collections')
->desc('Create collection')
->groups(['api', 'database'])
->label('event', 'databases.[databaseId].collections.[collectionId].create')
@@ -766,7 +766,7 @@ App::post('/v1/databases/:databaseId/collections')
->dynamic($collection, Response::MODEL_COLLECTION);
});
App::get('/v1/databases/:databaseId/collections')
Http::get('/v1/databases/:databaseId/collections')
->alias('/v1/database/collections', ['databaseId' => 'default'])
->desc('List collections')
->groups(['api', 'database'])
@@ -825,7 +825,7 @@ App::get('/v1/databases/:databaseId/collections')
]), Response::MODEL_COLLECTION_LIST);
});
App::get('/v1/databases/:databaseId/collections/:collectionId')
Http::get('/v1/databases/:databaseId/collections/:collectionId')
->alias('/v1/database/collections/:collectionId', ['databaseId' => 'default'])
->desc('Get collection')
->groups(['api', 'database'])
@@ -861,7 +861,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId')
$response->dynamic($collection, Response::MODEL_COLLECTION);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/logs')
Http::get('/v1/databases/:databaseId/collections/:collectionId/logs')
->alias('/v1/database/collections/:collectionId/logs', ['databaseId' => 'default'])
->desc('List collection logs')
->groups(['api', 'database'])
@@ -957,7 +957,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/logs')
});
App::put('/v1/databases/:databaseId/collections/:collectionId')
Http::put('/v1/databases/:databaseId/collections/:collectionId')
->alias('/v1/database/collections/:collectionId', ['databaseId' => 'default'])
->desc('Update collection')
->groups(['api', 'database', 'schema'])
@@ -1027,7 +1027,7 @@ App::put('/v1/databases/:databaseId/collections/:collectionId')
$response->dynamic($collection, Response::MODEL_COLLECTION);
});
App::delete('/v1/databases/:databaseId/collections/:collectionId')
Http::delete('/v1/databases/:databaseId/collections/:collectionId')
->alias('/v1/database/collections/:collectionId', ['databaseId' => 'default'])
->desc('Delete collection')
->groups(['api', 'database', 'schema'])
@@ -1083,7 +1083,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId')
$response->noContent();
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/string')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/string')
->alias('/v1/database/collections/:collectionId/attributes/string', ['databaseId' => 'default'])
->desc('Create string attribute')
->groups(['api', 'database', 'schema'])
@@ -1141,7 +1141,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/string
->dynamic($attribute, Response::MODEL_ATTRIBUTE_STRING);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/email')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/email')
->alias('/v1/database/collections/:collectionId/attributes/email', ['databaseId' => 'default'])
->desc('Create email attribute')
->groups(['api', 'database', 'schema'])
@@ -1185,7 +1185,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/email'
->dynamic($attribute, Response::MODEL_ATTRIBUTE_EMAIL);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/enum')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/enum')
->alias('/v1/database/collections/:collectionId/attributes/enum', ['databaseId' => 'default'])
->desc('Create enum attribute')
->groups(['api', 'database', 'schema'])
@@ -1245,7 +1245,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/enum')
->dynamic($attribute, Response::MODEL_ATTRIBUTE_ENUM);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/ip')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/ip')
->alias('/v1/database/collections/:collectionId/attributes/ip', ['databaseId' => 'default'])
->desc('Create IP address attribute')
->groups(['api', 'database', 'schema'])
@@ -1289,7 +1289,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/ip')
->dynamic($attribute, Response::MODEL_ATTRIBUTE_IP);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/url')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/url')
->alias('/v1/database/collections/:collectionId/attributes/url', ['databaseId' => 'default'])
->desc('Create URL attribute')
->groups(['api', 'database', 'schema'])
@@ -1333,7 +1333,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/url')
->dynamic($attribute, Response::MODEL_ATTRIBUTE_URL);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/integer')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/integer')
->alias('/v1/database/collections/:collectionId/attributes/integer', ['databaseId' => 'default'])
->desc('Create integer attribute')
->groups(['api', 'database', 'schema'])
@@ -1406,7 +1406,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/intege
->dynamic($attribute, Response::MODEL_ATTRIBUTE_INTEGER);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/float')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/float')
->alias('/v1/database/collections/:collectionId/attributes/float', ['databaseId' => 'default'])
->desc('Create float attribute')
->groups(['api', 'database', 'schema'])
@@ -1482,7 +1482,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/float'
->dynamic($attribute, Response::MODEL_ATTRIBUTE_FLOAT);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/boolean')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/boolean')
->alias('/v1/database/collections/:collectionId/attributes/boolean', ['databaseId' => 'default'])
->desc('Create boolean attribute')
->groups(['api', 'database', 'schema'])
@@ -1525,7 +1525,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/boolea
->dynamic($attribute, Response::MODEL_ATTRIBUTE_BOOLEAN);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/datetime')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/datetime')
->alias('/v1/database/collections/:collectionId/attributes/datetime', ['databaseId' => 'default'])
->desc('Create datetime attribute')
->groups(['api', 'database'])
@@ -1571,7 +1571,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/dateti
->dynamic($attribute, Response::MODEL_ATTRIBUTE_DATETIME);
});
App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/relationship')
Http::post('/v1/databases/:databaseId/collections/:collectionId/attributes/relationship')
->alias('/v1/database/collections/:collectionId/attributes/relationship', ['databaseId' => 'default'])
->desc('Create relationship attribute')
->groups(['api', 'database'])
@@ -1653,7 +1653,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/relati
->dynamic($attribute, Response::MODEL_ATTRIBUTE_RELATIONSHIP);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/attributes')
Http::get('/v1/databases/:databaseId/collections/:collectionId/attributes')
->alias('/v1/database/collections/:collectionId/attributes', ['databaseId' => 'default'])
->desc('List attributes')
->groups(['api', 'database'])
@@ -1728,7 +1728,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/attributes')
]), Response::MODEL_ATTRIBUTE_LIST);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/attributes/:key')
Http::get('/v1/databases/:databaseId/collections/:collectionId/attributes/:key')
->alias('/v1/database/collections/:collectionId/attributes/:key', ['databaseId' => 'default'])
->desc('Get attribute')
->groups(['api', 'database'])
@@ -1805,7 +1805,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/attributes/:key')
$response->dynamic($attribute, $model);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/string/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/string/:key')
->desc('Update string attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -1846,7 +1846,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/strin
->dynamic($attribute, Response::MODEL_ATTRIBUTE_STRING);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/email/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/email/:key')
->desc('Update email attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -1887,7 +1887,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/email
->dynamic($attribute, Response::MODEL_ATTRIBUTE_EMAIL);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/enum/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/enum/:key')
->desc('Update enum attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -1930,7 +1930,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/enum/
->dynamic($attribute, Response::MODEL_ATTRIBUTE_ENUM);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/ip/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/ip/:key')
->desc('Update IP address attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -1971,7 +1971,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/ip/:k
->dynamic($attribute, Response::MODEL_ATTRIBUTE_IP);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/url/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/url/:key')
->desc('Update URL attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -2012,7 +2012,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/url/:
->dynamic($attribute, Response::MODEL_ATTRIBUTE_URL);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/integer/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/integer/:key')
->desc('Update integer attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -2063,7 +2063,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/integ
->dynamic($attribute, Response::MODEL_ATTRIBUTE_INTEGER);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/float/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/float/:key')
->desc('Update float attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -2114,7 +2114,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/float
->dynamic($attribute, Response::MODEL_ATTRIBUTE_FLOAT);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/boolean/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/boolean/:key')
->desc('Update boolean attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -2154,7 +2154,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/boole
->dynamic($attribute, Response::MODEL_ATTRIBUTE_BOOLEAN);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/datetime/:key')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/datetime/:key')
->desc('Update dateTime attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -2194,7 +2194,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/datet
->dynamic($attribute, Response::MODEL_ATTRIBUTE_DATETIME);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/:key/relationship')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/:key/relationship')
->desc('Update relationship attribute')
->groups(['api', 'database', 'schema'])
->label('scope', 'collections.write')
@@ -2249,7 +2249,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/attributes/:key/
->dynamic($attribute, Response::MODEL_ATTRIBUTE_RELATIONSHIP);
});
App::delete('/v1/databases/:databaseId/collections/:collectionId/attributes/:key')
Http::delete('/v1/databases/:databaseId/collections/:collectionId/attributes/:key')
->alias('/v1/database/collections/:collectionId/attributes/:key', ['databaseId' => 'default'])
->desc('Delete attribute')
->groups(['api', 'database', 'schema'])
@@ -2360,7 +2360,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/attributes/:key
$response->noContent();
});
App::post('/v1/databases/:databaseId/collections/:collectionId/indexes')
Http::post('/v1/databases/:databaseId/collections/:collectionId/indexes')
->alias('/v1/database/collections/:collectionId/indexes', ['databaseId' => 'default'])
->desc('Create index')
->groups(['api', 'database'])
@@ -2520,7 +2520,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes')
->dynamic($index, Response::MODEL_INDEX);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/indexes')
Http::get('/v1/databases/:databaseId/collections/:collectionId/indexes')
->alias('/v1/database/collections/:collectionId/indexes', ['databaseId' => 'default'])
->desc('List indexes')
->groups(['api', 'database'])
@@ -2585,7 +2585,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/indexes')
]), Response::MODEL_INDEX_LIST);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/indexes/:key')
Http::get('/v1/databases/:databaseId/collections/:collectionId/indexes/:key')
->alias('/v1/database/collections/:collectionId/indexes/:key', ['databaseId' => 'default'])
->desc('Get index')
->groups(['api', 'database'])
@@ -2626,7 +2626,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/indexes/:key')
});
App::delete('/v1/databases/:databaseId/collections/:collectionId/indexes/:key')
Http::delete('/v1/databases/:databaseId/collections/:collectionId/indexes/:key')
->alias('/v1/database/collections/:collectionId/indexes/:key', ['databaseId' => 'default'])
->desc('Delete index')
->groups(['api', 'database'])
@@ -2692,7 +2692,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/indexes/:key')
$response->noContent();
});
App::post('/v1/databases/:databaseId/collections/:collectionId/documents')
Http::post('/v1/databases/:databaseId/collections/:collectionId/documents')
->alias('/v1/database/collections/:collectionId/documents', ['databaseId' => 'default'])
->desc('Create document')
->groups(['api', 'database'])
@@ -2932,7 +2932,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents')
->dynamic($document, Response::MODEL_DOCUMENT);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/documents')
Http::get('/v1/databases/:databaseId/collections/:collectionId/documents')
->alias('/v1/database/collections/:collectionId/documents', ['databaseId' => 'default'])
->desc('List documents')
->groups(['api', 'database'])
@@ -3059,7 +3059,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents')
]), Response::MODEL_DOCUMENT_LIST);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId')
Http::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId')
->alias('/v1/database/collections/:collectionId/documents/:documentId', ['databaseId' => 'default'])
->desc('Get document')
->groups(['api', 'database'])
@@ -3154,7 +3154,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen
$response->dynamic($document, Response::MODEL_DOCUMENT);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId/logs')
Http::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId/logs')
->alias('/v1/database/collections/:collectionId/documents/:documentId/logs', ['databaseId' => 'default'])
->desc('List document logs')
->groups(['api', 'database'])
@@ -3255,7 +3255,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen
]), Response::MODEL_LOG_LIST);
});
App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId')
Http::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId')
->alias('/v1/database/collections/:collectionId/documents/:documentId', ['databaseId' => 'default'])
->desc('Update document')
->groups(['api', 'database'])
@@ -3484,7 +3484,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum
$response->dynamic($document, Response::MODEL_DOCUMENT);
});
App::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId')
Http::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:documentId')
->alias('/v1/database/collections/:collectionId/documents/:documentId', ['databaseId' => 'default'])
->desc('Delete document')
->groups(['api', 'database'])
@@ -3600,7 +3600,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:docu
$response->noContent();
});
App::get('/v1/databases/usage')
Http::get('/v1/databases/usage')
->desc('Get usage stats for the database')
->groups(['api', 'database'])
->label('scope', 'collections.read')
@@ -3616,7 +3616,7 @@ App::get('/v1/databases/usage')
->action(function (string $range, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -3718,7 +3718,7 @@ App::get('/v1/databases/usage')
$response->dynamic($usage, Response::MODEL_USAGE_DATABASES);
});
App::get('/v1/databases/:databaseId/usage')
Http::get('/v1/databases/:databaseId/usage')
->desc('Get usage stats for the database')
->groups(['api', 'database'])
->label('scope', 'collections.read')
@@ -3735,7 +3735,7 @@ App::get('/v1/databases/:databaseId/usage')
->action(function (string $databaseId, string $range, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -3827,7 +3827,7 @@ App::get('/v1/databases/:databaseId/usage')
$response->dynamic($usage, Response::MODEL_USAGE_DATABASE);
});
App::get('/v1/databases/:databaseId/collections/:collectionId/usage')
Http::get('/v1/databases/:databaseId/collections/:collectionId/usage')
->alias('/v1/database/:collectionId/usage', ['databaseId' => 'default'])
->desc('Get usage stats for a collection')
->groups(['api', 'database'])
@@ -3854,7 +3854,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/usage')
}
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
+41 -41
View File
@@ -12,7 +12,7 @@ use Appwrite\Utopia\Response\Model\Rule;
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Messaging\Adapter\Realtime;
use Utopia\Validator\Assoc;
use Utopia\Http\Validator\Assoc;
use Appwrite\Usage\Stats;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Permission;
@@ -29,21 +29,21 @@ use Appwrite\Task\Validator\Cron;
use Appwrite\Utopia\Database\Validator\Queries\Deployments;
use Appwrite\Utopia\Database\Validator\Queries\Executions;
use Appwrite\Utopia\Database\Validator\Queries\Functions;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\DateTime;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Text;
use Utopia\Validator\Range;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\Range;
use Utopia\Http\Validator\WhiteList;
use Utopia\Config\Config;
use Executor\Executor;
use Utopia\CLI\Console;
use Utopia\Database\Validator\Roles;
use Utopia\Validator\Boolean;
use Utopia\Http\Validator\Boolean;
use Utopia\Database\Exception\Duplicate as DuplicateException;
use MaxMind\Db\Reader;
use Utopia\VCS\Adapter\Git\GitHub;
@@ -54,8 +54,8 @@ $redeployVcs = function (Request $request, Document $function, Document $project
$deploymentId = ID::unique();
$entrypoint = $function->getAttribute('entrypoint', '');
$providerInstallationId = $installation->getAttribute('providerInstallationId', '');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$owner = $github->getOwnerName($providerInstallationId);
$providerRepositoryId = $function->getAttribute('providerRepositoryId', '');
@@ -119,7 +119,7 @@ $redeployVcs = function (Request $request, Document $function, Document $project
->trigger();
};
App::post('/v1/functions')
Http::post('/v1/functions')
->groups(['api', 'functions'])
->desc('Create function')
->label('scope', 'functions.write')
@@ -139,7 +139,7 @@ App::post('/v1/functions')
->param('execute', [], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of role strings with execution permissions. By default no user is granted with any execute permissions. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.', true)
->param('events', [], new ArrayList(new FunctionEvent(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.', true)
->param('schedule', '', new Cron(), 'Schedule CRON syntax.', true)
->param('timeout', 15, new Range(1, (int) App::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Function maximum execution time in seconds.', true)
->param('timeout', 15, new Range(1, (int) Http::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Function maximum execution time in seconds.', true)
->param('enabled', true, new Boolean(), 'Is function enabled? When set to \'disabled\', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled.', true)
->param('logging', true, new Boolean(), 'Whether executions will be logged. When set to false, executions will not be logged, but will reduce resource used by your Appwrite project.', true)
->param('entrypoint', '', new Text(1028, 0), 'Entrypoint File. This path is relative to the "providerRootDirectory".', true)
@@ -219,7 +219,7 @@ App::post('/v1/functions')
$schedule = Authorization::skip(
fn () => $dbForConsole->createDocument('schedules', new Document([
'region' => App::getEnv('_APP_REGION', 'default'), // Todo replace with projects region
'region' => Http::getEnv('_APP_REGION', 'default'), // Todo replace with projects region
'resourceType' => 'function',
'resourceId' => $function->getId(),
'resourceInternalId' => $function->getInternalId(),
@@ -264,7 +264,7 @@ App::post('/v1/functions')
$redeployVcs($request, $function, $project, $installation, $dbForProject, $template, $github);
}
$functionsDomain = App::getEnv('_APP_DOMAIN_FUNCTIONS', '');
$functionsDomain = Http::getEnv('_APP_DOMAIN_FUNCTIONS', '');
if (!empty($functionsDomain)) {
$ruleId = ID::unique();
$routeSubdomain = ID::unique();
@@ -333,7 +333,7 @@ App::post('/v1/functions')
->dynamic($function, Response::MODEL_FUNCTION);
});
App::get('/v1/functions')
Http::get('/v1/functions')
->groups(['api', 'functions'])
->desc('List functions')
->label('scope', 'functions.read')
@@ -381,7 +381,7 @@ App::get('/v1/functions')
]), Response::MODEL_FUNCTION_LIST);
});
App::get('/v1/functions/runtimes')
Http::get('/v1/functions/runtimes')
->groups(['api', 'functions'])
->desc('List runtimes')
->label('scope', 'functions.read')
@@ -408,7 +408,7 @@ App::get('/v1/functions/runtimes')
]), Response::MODEL_RUNTIME_LIST);
});
App::get('/v1/functions/:functionId')
Http::get('/v1/functions/:functionId')
->groups(['api', 'functions'])
->desc('Get function')
->label('scope', 'functions.read')
@@ -432,7 +432,7 @@ App::get('/v1/functions/:functionId')
$response->dynamic($function, Response::MODEL_FUNCTION);
});
App::get('/v1/functions/:functionId/usage')
Http::get('/v1/functions/:functionId/usage')
->desc('Get function usage')
->groups(['api', 'functions', 'usage'])
->label('scope', 'functions.read')
@@ -455,7 +455,7 @@ App::get('/v1/functions/:functionId/usage')
}
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -542,7 +542,7 @@ App::get('/v1/functions/:functionId/usage')
$response->dynamic($usage, Response::MODEL_USAGE_FUNCTION);
});
App::get('/v1/functions/usage')
Http::get('/v1/functions/usage')
->desc('Get functions usage')
->groups(['api', 'functions', 'usage'])
->label('scope', 'functions.read')
@@ -558,7 +558,7 @@ App::get('/v1/functions/usage')
->action(function (string $range, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -645,7 +645,7 @@ App::get('/v1/functions/usage')
$response->dynamic($usage, Response::MODEL_USAGE_FUNCTIONS);
});
App::put('/v1/functions/:functionId')
Http::put('/v1/functions/:functionId')
->groups(['api', 'functions'])
->desc('Update function')
->label('scope', 'functions.write')
@@ -665,7 +665,7 @@ App::put('/v1/functions/:functionId')
->param('execute', [], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of role strings with execution permissions. By default no user is granted with any execute permissions. [learn more about roles](https://appwrite.io/docs/permissions#permission-roles). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.', true)
->param('events', [], new ArrayList(new FunctionEvent(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.', true)
->param('schedule', '', new Cron(), 'Schedule CRON syntax.', true)
->param('timeout', 15, new Range(1, (int) App::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Maximum execution time in seconds.', true)
->param('timeout', 15, new Range(1, (int) Http::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Maximum execution time in seconds.', true)
->param('enabled', true, new Boolean(), 'Is function enabled? When set to \'disabled\', users cannot access the function but Server SDKs with and API key can still access the function. No data is lost when this is toggled.', true)
->param('logging', true, new Boolean(), 'Whether executions will be logged. When set to false, executions will not be logged, but will reduce resource used by your Appwrite project.', true)
->param('entrypoint', '', new Text(1028, 0), 'Entrypoint File. This path is relative to the "providerRootDirectory".', true)
@@ -823,7 +823,7 @@ App::put('/v1/functions/:functionId')
$response->dynamic($function, Response::MODEL_FUNCTION);
});
App::get('/v1/functions/:functionId/deployments/:deploymentId/download')
Http::get('/v1/functions/:functionId/deployments/:deploymentId/download')
->groups(['api', 'functions'])
->desc('Download Deployment')
->label('scope', 'functions.read')
@@ -910,7 +910,7 @@ App::get('/v1/functions/:functionId/deployments/:deploymentId/download')
}
});
App::patch('/v1/functions/:functionId/deployments/:deploymentId')
Http::patch('/v1/functions/:functionId/deployments/:deploymentId')
->groups(['api', 'functions'])
->desc('Update function deployment')
->label('scope', 'functions.write')
@@ -972,7 +972,7 @@ App::patch('/v1/functions/:functionId/deployments/:deploymentId')
$response->dynamic($function, Response::MODEL_FUNCTION);
});
App::delete('/v1/functions/:functionId')
Http::delete('/v1/functions/:functionId')
->groups(['api', 'functions'])
->desc('Delete function')
->label('scope', 'functions.write')
@@ -1019,7 +1019,7 @@ App::delete('/v1/functions/:functionId')
$response->noContent();
});
App::post('/v1/functions/:functionId/deployments')
Http::post('/v1/functions/:functionId/deployments')
->groups(['api', 'functions'])
->desc('Create deployment')
->label('scope', 'functions.write')
@@ -1080,7 +1080,7 @@ App::post('/v1/functions/:functionId/deployments')
}
$fileExt = new FileExt([FileExt::TYPE_GZIP]);
$fileSizeValidator = new FileSize(App::getEnv('_APP_FUNCTIONS_SIZE_LIMIT', '30000000'));
$fileSizeValidator = new FileSize(Http::getEnv('_APP_FUNCTIONS_SIZE_LIMIT', '30000000'));
$upload = new Upload();
// Make sure we handle a single file and multiple files the same way
@@ -1238,7 +1238,7 @@ App::post('/v1/functions/:functionId/deployments')
->dynamic($deployment, Response::MODEL_DEPLOYMENT);
});
App::get('/v1/functions/:functionId/deployments')
Http::get('/v1/functions/:functionId/deployments')
->groups(['api', 'functions'])
->desc('List deployments')
->label('scope', 'functions.read')
@@ -1308,7 +1308,7 @@ App::get('/v1/functions/:functionId/deployments')
]), Response::MODEL_DEPLOYMENT_LIST);
});
App::get('/v1/functions/:functionId/deployments/:deploymentId')
Http::get('/v1/functions/:functionId/deployments/:deploymentId')
->groups(['api', 'functions'])
->desc('Get deployment')
->label('scope', 'functions.read')
@@ -1350,7 +1350,7 @@ App::get('/v1/functions/:functionId/deployments/:deploymentId')
$response->dynamic($deployment, Response::MODEL_DEPLOYMENT);
});
App::delete('/v1/functions/:functionId/deployments/:deploymentId')
Http::delete('/v1/functions/:functionId/deployments/:deploymentId')
->groups(['api', 'functions'])
->desc('Delete deployment')
->label('scope', 'functions.write')
@@ -1414,7 +1414,7 @@ App::delete('/v1/functions/:functionId/deployments/:deploymentId')
$response->noContent();
});
App::post('/v1/functions/:functionId/deployments/:deploymentId/builds/:buildId')
Http::post('/v1/functions/:functionId/deployments/:deploymentId/builds/:buildId')
->groups(['api', 'functions'])
->desc('Create build')
->label('scope', 'functions.write')
@@ -1483,7 +1483,7 @@ App::post('/v1/functions/:functionId/deployments/:deploymentId/builds/:buildId')
$response->noContent();
});
App::post('/v1/functions/:functionId/executions')
Http::post('/v1/functions/:functionId/executions')
->groups(['api', 'functions'])
->desc('Create execution')
->label('scope', 'execution.write')
@@ -1569,7 +1569,7 @@ App::post('/v1/functions/:functionId/executions')
}
if (!$current->isEmpty()) {
$jwtObj = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.
$jwtObj = new JWT(Http::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.
$jwt = $jwtObj->encode([
'userId' => $user->getId(),
'sessionId' => $current->getId(),
@@ -1690,7 +1690,7 @@ App::post('/v1/functions/:functionId/executions')
]);
/** Execute function */
$executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST'));
$executor = new Executor(Http::getEnv('_APP_EXECUTOR_HOST'));
try {
$version = $function->getAttribute('version', 'v2');
$command = $runtime['startCommand'];
@@ -1772,7 +1772,7 @@ App::post('/v1/functions/:functionId/executions')
->dynamic($execution, Response::MODEL_EXECUTION);
});
App::get('/v1/functions/:functionId/executions')
Http::get('/v1/functions/:functionId/executions')
->groups(['api', 'functions'])
->desc('List executions')
->label('scope', 'execution.read')
@@ -1847,7 +1847,7 @@ App::get('/v1/functions/:functionId/executions')
]), Response::MODEL_EXECUTION_LIST);
});
App::get('/v1/functions/:functionId/executions/:executionId')
Http::get('/v1/functions/:functionId/executions/:executionId')
->groups(['api', 'functions'])
->desc('Get execution')
->label('scope', 'execution.read')
@@ -1896,7 +1896,7 @@ App::get('/v1/functions/:functionId/executions/:executionId')
// Variables
App::post('/v1/functions/:functionId/variables')
Http::post('/v1/functions/:functionId/variables')
->desc('Create variable')
->groups(['api', 'functions'])
->label('scope', 'functions.write')
@@ -1960,7 +1960,7 @@ App::post('/v1/functions/:functionId/variables')
->dynamic($variable, Response::MODEL_VARIABLE);
});
App::get('/v1/functions/:functionId/variables')
Http::get('/v1/functions/:functionId/variables')
->desc('List variables')
->groups(['api', 'functions'])
->label('scope', 'functions.read')
@@ -1987,7 +1987,7 @@ App::get('/v1/functions/:functionId/variables')
]), Response::MODEL_VARIABLE_LIST);
});
App::get('/v1/functions/:functionId/variables/:variableId')
Http::get('/v1/functions/:functionId/variables/:variableId')
->desc('Get variable')
->groups(['api', 'functions'])
->label('scope', 'functions.read')
@@ -2026,7 +2026,7 @@ App::get('/v1/functions/:functionId/variables/:variableId')
$response->dynamic($variable, Response::MODEL_VARIABLE);
});
App::put('/v1/functions/:functionId/variables/:variableId')
Http::put('/v1/functions/:functionId/variables/:variableId')
->desc('Update variable')
->groups(['api', 'functions'])
->label('scope', 'functions.write')
@@ -2087,7 +2087,7 @@ App::put('/v1/functions/:functionId/variables/:variableId')
$response->dynamic($variable, Response::MODEL_VARIABLE);
});
App::delete('/v1/functions/:functionId/variables/:variableId')
Http::delete('/v1/functions/:functionId/variables/:variableId')
->desc('Delete variable')
->groups(['api', 'functions'])
->label('scope', 'functions.write')
+12 -12
View File
@@ -12,12 +12,12 @@ use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use Swoole\Coroutine\WaitGroup;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Document;
use Utopia\Validator\JSON;
use Utopia\Validator\Text;
use Utopia\Http\Validator\JSON;
use Utopia\Http\Validator\Text;
App::get('/v1/graphql')
Http::get('/v1/graphql')
->desc('GraphQL endpoint')
->groups(['graphql'])
->label('scope', 'graphql')
@@ -57,7 +57,7 @@ App::get('/v1/graphql')
->json($output);
});
App::post('/v1/graphql/mutation')
Http::post('/v1/graphql/mutation')
->desc('GraphQL endpoint')
->groups(['graphql'])
->label('scope', 'graphql')
@@ -102,7 +102,7 @@ App::post('/v1/graphql/mutation')
->json($output);
});
App::post('/v1/graphql')
Http::post('/v1/graphql')
->desc('GraphQL endpoint')
->groups(['graphql'])
->label('scope', 'graphql')
@@ -161,9 +161,9 @@ function execute(
Adapter $promiseAdapter,
array $query
): array {
$maxBatchSize = App::getEnv('_APP_GRAPHQL_MAX_BATCH_SIZE', 10);
$maxComplexity = App::getEnv('_APP_GRAPHQL_MAX_COMPLEXITY', 250);
$maxDepth = App::getEnv('_APP_GRAPHQL_MAX_DEPTH', 3);
$maxBatchSize = Http::getEnv('_APP_GRAPHQL_MAX_BATCH_SIZE', 10);
$maxComplexity = Http::getEnv('_APP_GRAPHQL_MAX_COMPLEXITY', 250);
$maxDepth = Http::getEnv('_APP_GRAPHQL_MAX_DEPTH', 3);
if (!empty($query) && !isset($query[0])) {
$query = [$query];
@@ -183,12 +183,12 @@ function execute(
$flags = DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE;
$validations = GraphQL::getStandardValidationRules();
if (App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled') {
if (Http::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled') {
$validations[] = new DisableIntrospection();
$validations[] = new QueryComplexity($maxComplexity);
$validations[] = new QueryDepth($maxDepth);
}
if (App::getMode() === App::MODE_TYPE_PRODUCTION) {
if (Http::getMode() === Http::MODE_TYPE_PRODUCTION) {
$flags = DebugFlag::NONE;
}
@@ -289,7 +289,7 @@ function processResult($result, $debugFlags): array
);
}
App::shutdown()
Http::shutdown()
->groups(['schema'])
->inject('project')
->action(function (Document $project) {
+24 -24
View File
@@ -4,7 +4,7 @@ use Appwrite\ClamAV\Network;
use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Config\Config;
use Utopia\Database\Document;
use Utopia\Pools\Group;
@@ -15,7 +15,7 @@ use Utopia\Storage\Device;
use Utopia\Storage\Device\Local;
use Utopia\Storage\Storage;
App::get('/v1/health')
Http::get('/v1/health')
->desc('Get HTTP')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -38,7 +38,7 @@ App::get('/v1/health')
$response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS);
});
App::get('/v1/health/version')
Http::get('/v1/health/version')
->desc('Get version')
->groups(['api', 'health'])
->label('scope', 'public')
@@ -50,7 +50,7 @@ App::get('/v1/health/version')
$response->dynamic(new Document([ 'version' => APP_VERSION_STABLE ]), Response::MODEL_HEALTH_VERSION);
});
App::get('/v1/health/db')
Http::get('/v1/health/db')
->desc('Get DB')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -108,7 +108,7 @@ App::get('/v1/health/db')
]), Response::MODEL_HEALTH_STATUS_LIST);
});
App::get('/v1/health/cache')
Http::get('/v1/health/cache')
->desc('Get cache')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -165,7 +165,7 @@ App::get('/v1/health/cache')
]), Response::MODEL_HEALTH_STATUS_LIST);
});
App::get('/v1/health/queue')
Http::get('/v1/health/queue')
->desc('Get queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -222,7 +222,7 @@ App::get('/v1/health/queue')
]), Response::MODEL_HEALTH_STATUS_LIST);
});
App::get('/v1/health/pubsub')
Http::get('/v1/health/pubsub')
->desc('Get pubsub')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -279,7 +279,7 @@ App::get('/v1/health/pubsub')
]), Response::MODEL_HEALTH_STATUS_LIST);
});
App::get('/v1/health/time')
Http::get('/v1/health/time')
->desc('Get time')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -336,7 +336,7 @@ App::get('/v1/health/time')
$response->dynamic(new Document($output), Response::MODEL_HEALTH_TIME);
});
App::get('/v1/health/queue/webhooks')
Http::get('/v1/health/queue/webhooks')
->desc('Get webhooks queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -353,7 +353,7 @@ App::get('/v1/health/queue/webhooks')
$response->dynamic(new Document([ 'size' => Resque::size(Event::WEBHOOK_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/logs')
Http::get('/v1/health/queue/logs')
->desc('Get logs queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -370,7 +370,7 @@ App::get('/v1/health/queue/logs')
$response->dynamic(new Document([ 'size' => Resque::size(Event::AUDITS_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/certificates')
Http::get('/v1/health/queue/certificates')
->desc('Get certificates queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -387,7 +387,7 @@ App::get('/v1/health/queue/certificates')
$response->dynamic(new Document([ 'size' => Resque::size(Event::CERTIFICATES_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/builds')
Http::get('/v1/health/queue/builds')
->desc('Get builds queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -404,7 +404,7 @@ App::get('/v1/health/queue/builds')
$response->dynamic(new Document([ 'size' => Resque::size(Event::BUILDS_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/databases')
Http::get('/v1/health/queue/databases')
->desc('Get databases queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -421,7 +421,7 @@ App::get('/v1/health/queue/databases')
$response->dynamic(new Document([ 'size' => Resque::size(Event::DATABASE_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/deletes')
Http::get('/v1/health/queue/deletes')
->desc('Get deletes queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -438,7 +438,7 @@ App::get('/v1/health/queue/deletes')
$response->dynamic(new Document([ 'size' => Resque::size(Event::DELETE_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/mails')
Http::get('/v1/health/queue/mails')
->desc('Get mails queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -455,7 +455,7 @@ App::get('/v1/health/queue/mails')
$response->dynamic(new Document([ 'size' => Resque::size(Event::MAILS_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/messaging')
Http::get('/v1/health/queue/messaging')
->desc('Get messaging queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -472,7 +472,7 @@ App::get('/v1/health/queue/messaging')
$response->dynamic(new Document([ 'size' => Resque::size(Event::MESSAGING_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/migrations')
Http::get('/v1/health/queue/migrations')
->desc('Get migrations queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -489,7 +489,7 @@ App::get('/v1/health/queue/migrations')
$response->dynamic(new Document([ 'size' => Resque::size(Event::MIGRATIONS_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/queue/functions')
Http::get('/v1/health/queue/functions')
->desc('Get functions queue')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -507,7 +507,7 @@ App::get('/v1/health/queue/functions')
$response->dynamic(new Document([ 'size' => $client->sumProcessingJobs() ]), Response::MODEL_HEALTH_QUEUE);
}, ['response']);
App::get('/v1/health/storage/local')
Http::get('/v1/health/storage/local')
->desc('Get local storage')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -550,7 +550,7 @@ App::get('/v1/health/storage/local')
$response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS);
});
App::get('/v1/health/anti-virus')
Http::get('/v1/health/anti-virus')
->desc('Get antivirus')
->groups(['api', 'health'])
->label('scope', 'health.read')
@@ -569,13 +569,13 @@ App::get('/v1/health/anti-virus')
'version' => ''
];
if (App::getEnv('_APP_STORAGE_ANTIVIRUS') === 'disabled') { // Check if scans are enabled
if (Http::getEnv('_APP_STORAGE_ANTIVIRUS') === 'disabled') { // Check if scans are enabled
$output['status'] = 'disabled';
$output['version'] = '';
} else {
$antivirus = new Network(
App::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),
(int) App::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)
Http::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),
(int) Http::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)
);
try {
@@ -589,7 +589,7 @@ App::get('/v1/health/anti-virus')
$response->dynamic(new Document($output), Response::MODEL_HEALTH_ANTIVIRUS);
});
App::get('/v1/health/stats') // Currently only used internally
Http::get('/v1/health/stats') // Currently only used internally
->desc('Get system stats')
->groups(['api', 'health'])
->label('scope', 'root')
+9 -9
View File
@@ -3,12 +3,12 @@
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Request;
use MaxMind\Db\Reader;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Config\Config;
use Utopia\Database\Document;
use Utopia\Locale\Locale;
App::get('/v1/locale')
Http::get('/v1/locale')
->desc('Get user locale')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -68,7 +68,7 @@ App::get('/v1/locale')
$response->dynamic(new Document($output), Response::MODEL_LOCALE);
});
App::get('/v1/locale/codes')
Http::get('/v1/locale/codes')
->desc('List Locale Codes')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -90,7 +90,7 @@ App::get('/v1/locale/codes')
]), Response::MODEL_LOCALE_CODE_LIST);
});
App::get('/v1/locale/countries')
Http::get('/v1/locale/countries')
->desc('List countries')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -123,7 +123,7 @@ App::get('/v1/locale/countries')
$response->dynamic(new Document(['countries' => $output, 'total' => \count($output)]), Response::MODEL_COUNTRY_LIST);
});
App::get('/v1/locale/countries/eu')
Http::get('/v1/locale/countries/eu')
->desc('List EU countries')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -158,7 +158,7 @@ App::get('/v1/locale/countries/eu')
$response->dynamic(new Document(['countries' => $output, 'total' => \count($output)]), Response::MODEL_COUNTRY_LIST);
});
App::get('/v1/locale/countries/phones')
Http::get('/v1/locale/countries/phones')
->desc('List countries phone codes')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -192,7 +192,7 @@ App::get('/v1/locale/countries/phones')
$response->dynamic(new Document(['phones' => $output, 'total' => \count($output)]), Response::MODEL_PHONE_LIST);
});
App::get('/v1/locale/continents')
Http::get('/v1/locale/continents')
->desc('List continents')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -224,7 +224,7 @@ App::get('/v1/locale/continents')
$response->dynamic(new Document(['continents' => $output, 'total' => \count($output)]), Response::MODEL_CONTINENT_LIST);
});
App::get('/v1/locale/currencies')
Http::get('/v1/locale/currencies')
->desc('List currencies')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
@@ -247,7 +247,7 @@ App::get('/v1/locale/currencies')
});
App::get('/v1/locale/languages')
Http::get('/v1/locale/languages')
->desc('List languages')
->groups(['api', 'locale'])
->label('scope', 'locale.read')
+37 -37
View File
@@ -10,7 +10,7 @@ use Appwrite\Role;
use Appwrite\Utopia\Database\Validator\Queries\Migrations;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
@@ -21,16 +21,16 @@ use Utopia\Migration\Sources\Appwrite;
use Utopia\Migration\Sources\Firebase;
use Utopia\Migration\Sources\NHost;
use Utopia\Migration\Sources\Supabase;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Host;
use Utopia\Validator\Integer;
use Utopia\Validator\Text;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Host;
use Utopia\Http\Validator\Integer;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\URL;
use Utopia\Http\Validator\WhiteList;
include_once __DIR__ . '/../shared/api.php';
App::post('/v1/migrations/appwrite')
Http::post('/v1/migrations/appwrite')
->groups(['api', 'migrations'])
->desc('Migrate Appwrite Data')
->label('scope', 'migrations.write')
@@ -84,7 +84,7 @@ App::post('/v1/migrations/appwrite')
->dynamic($migration, Response::MODEL_MIGRATION);
});
App::post('/v1/migrations/firebase/oauth')
Http::post('/v1/migrations/firebase/oauth')
->groups(['api', 'migrations'])
->desc('Migrate Firebase Data (OAuth)')
->label('scope', 'migrations.write')
@@ -108,8 +108,8 @@ App::post('/v1/migrations/firebase/oauth')
->inject('request')
->action(function (array $resources, string $projectId, Response $response, Database $dbForProject, Database $dbForConsole, Document $project, Document $user, Event $events, Request $request) {
$firebase = new OAuth2Firebase(
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
$request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'
);
@@ -186,7 +186,7 @@ App::post('/v1/migrations/firebase/oauth')
->dynamic($migration, Response::MODEL_MIGRATION);
});
App::post('/v1/migrations/firebase')
Http::post('/v1/migrations/firebase')
->groups(['api', 'migrations'])
->desc('Migrate Firebase Data (Service Account)')
->label('scope', 'migrations.write')
@@ -236,7 +236,7 @@ App::post('/v1/migrations/firebase')
->dynamic($migration, Response::MODEL_MIGRATION);
});
App::post('/v1/migrations/supabase')
Http::post('/v1/migrations/supabase')
->groups(['api', 'migrations'])
->desc('Migrate Supabase Data')
->label('scope', 'migrations.write')
@@ -296,7 +296,7 @@ App::post('/v1/migrations/supabase')
->dynamic($migration, Response::MODEL_MIGRATION);
});
App::post('/v1/migrations/nhost')
Http::post('/v1/migrations/nhost')
->groups(['api', 'migrations'])
->desc('Migrate NHost Data')
->label('scope', 'migrations.write')
@@ -358,7 +358,7 @@ App::post('/v1/migrations/nhost')
->dynamic($migration, Response::MODEL_MIGRATION);
});
App::get('/v1/migrations')
Http::get('/v1/migrations')
->groups(['api', 'migrations'])
->desc('List Migrations')
->label('scope', 'migrations.read')
@@ -405,7 +405,7 @@ App::get('/v1/migrations')
]), Response::MODEL_MIGRATION_LIST);
});
App::get('/v1/migrations/:migrationId')
Http::get('/v1/migrations/:migrationId')
->groups(['api', 'migrations'])
->desc('Get Migration')
->label('scope', 'migrations.read')
@@ -429,7 +429,7 @@ App::get('/v1/migrations/:migrationId')
$response->dynamic($migration, Response::MODEL_MIGRATION);
});
App::get('/v1/migrations/appwrite/report')
Http::get('/v1/migrations/appwrite/report')
->groups(['api', 'migrations'])
->desc('Generate a report on Appwrite Data')
->label('scope', 'migrations.write')
@@ -460,7 +460,7 @@ App::get('/v1/migrations/appwrite/report')
}
});
App::get('/v1/migrations/firebase/report')
Http::get('/v1/migrations/firebase/report')
->groups(['api', 'migrations'])
->desc('Generate a report on Firebase Data')
->label('scope', 'migrations.write')
@@ -486,7 +486,7 @@ App::get('/v1/migrations/firebase/report')
}
});
App::get('/v1/migrations/firebase/report/oauth')
Http::get('/v1/migrations/firebase/report/oauth')
->groups(['api', 'migrations'])
->desc('Generate a report on Firebase Data using OAuth')
->label('scope', 'migrations.write')
@@ -505,8 +505,8 @@ App::get('/v1/migrations/firebase/report/oauth')
->inject('dbForConsole')
->action(function (array $resources, string $projectId, Response $response, Request $request, Document $user, Database $dbForConsole) {
$firebase = new OAuth2Firebase(
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
$request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'
);
@@ -527,7 +527,7 @@ App::get('/v1/migrations/firebase/report/oauth')
throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);
}
if (App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', '') === '' || App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', '') === '') {
if (Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', '') === '' || Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', '') === '') {
throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);
}
@@ -577,7 +577,7 @@ App::get('/v1/migrations/firebase/report/oauth')
->dynamic(new Document($report), Response::MODEL_MIGRATION_REPORT);
});
App::get('/v1/migrations/firebase/connect')
Http::get('/v1/migrations/firebase/connect')
->desc('Authorize with firebase')
->groups(['api', 'migrations'])
->label('scope', 'migrations.write')
@@ -607,8 +607,8 @@ App::get('/v1/migrations/firebase/connect')
$dbForConsole->updateDocument('users', $user->getId(), $user);
$oauth2 = new OAuth2Firebase(
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
$request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'
);
$url = $oauth2->getLoginURL();
@@ -619,7 +619,7 @@ App::get('/v1/migrations/firebase/connect')
->redirect($url);
});
App::get('/v1/migrations/firebase/redirect')
Http::get('/v1/migrations/firebase/redirect')
->desc('Capture and receive data on Firebase authorization')
->groups(['api', 'migrations'])
->label('scope', 'public')
@@ -662,8 +662,8 @@ App::get('/v1/migrations/firebase/redirect')
// OAuth Authroization
if (!empty($code)) {
$oauth2 = new OAuth2Firebase(
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
$request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'
);
@@ -731,7 +731,7 @@ App::get('/v1/migrations/firebase/redirect')
->redirect($redirect);
});
App::get('/v1/migrations/firebase/projects')
Http::get('/v1/migrations/firebase/projects')
->desc('List Firebase Projects')
->groups(['api', 'migrations'])
->label('scope', 'migrations.read')
@@ -749,8 +749,8 @@ App::get('/v1/migrations/firebase/projects')
->inject('request')
->action(function (Document $user, Response $response, Document $project, Database $dbForConsole, Request $request) {
$firebase = new OAuth2Firebase(
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', ''),
Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', ''),
$request->getProtocol() . '://' . $request->getHostname() . '/v1/migrations/firebase/redirect'
);
@@ -771,7 +771,7 @@ App::get('/v1/migrations/firebase/projects')
throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);
}
if (App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', '') === '' || App::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', '') === '') {
if (Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_ID', '') === '' || Http::getEnv('_APP_MIGRATIONS_FIREBASE_CLIENT_SECRET', '') === '') {
throw new Exception(Exception::USER_IDENTITY_NOT_FOUND);
}
@@ -820,7 +820,7 @@ App::get('/v1/migrations/firebase/projects')
]), Response::MODEL_MIGRATION_FIREBASE_PROJECT_LIST);
});
App::get('/v1/migrations/firebase/deauthorize')
Http::get('/v1/migrations/firebase/deauthorize')
->desc('Revoke Appwrite\'s authorization to access Firebase Projects')
->groups(['api', 'migrations'])
->label('scope', 'migrations.write')
@@ -848,7 +848,7 @@ App::get('/v1/migrations/firebase/deauthorize')
$response->noContent();
});
App::get('/v1/migrations/supabase/report')
Http::get('/v1/migrations/supabase/report')
->groups(['api', 'migrations'])
->desc('Generate a report on Supabase Data')
->label('scope', 'migrations.write')
@@ -880,7 +880,7 @@ App::get('/v1/migrations/supabase/report')
}
});
App::get('/v1/migrations/nhost/report')
Http::get('/v1/migrations/nhost/report')
->groups(['api', 'migrations'])
->desc('Generate a report on NHost Data')
->label('scope', 'migrations.write')
@@ -912,7 +912,7 @@ App::get('/v1/migrations/nhost/report')
}
});
App::patch('/v1/migrations/:migrationId')
Http::patch('/v1/migrations/:migrationId')
->groups(['api', 'migrations'])
->desc('Retry Migration')
->label('scope', 'migrations.write')
@@ -958,7 +958,7 @@ App::patch('/v1/migrations/:migrationId')
$response->noContent();
});
App::delete('/v1/migrations/:migrationId')
Http::delete('/v1/migrations/:migrationId')
->groups(['api', 'migrations'])
->desc('Delete Migration')
->label('scope', 'migrations.write')
+10 -10
View File
@@ -2,7 +2,7 @@
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate as DuplicateException;
@@ -12,11 +12,11 @@ use Utopia\Database\Helpers\Role;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\WhiteList;
use Utopia\Database\DateTime;
App::get('/v1/project/usage')
Http::get('/v1/project/usage')
->desc('Get usage stats for a project')
->groups(['api'])
->label('scope', 'projects.read')
@@ -31,7 +31,7 @@ App::get('/v1/project/usage')
->inject('dbForProject')
->action(function (string $range, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -120,7 +120,7 @@ App::get('/v1/project/usage')
// Variables
App::post('/v1/project/variables')
Http::post('/v1/project/variables')
->desc('Create Variable')
->groups(['api'])
->label('scope', 'projects.write')
@@ -175,7 +175,7 @@ App::post('/v1/project/variables')
->dynamic($variable, Response::MODEL_VARIABLE);
});
App::get('/v1/project/variables')
Http::get('/v1/project/variables')
->desc('List Variables')
->groups(['api'])
->label('scope', 'projects.read')
@@ -200,7 +200,7 @@ App::get('/v1/project/variables')
]), Response::MODEL_VARIABLE_LIST);
});
App::get('/v1/project/variables/:variableId')
Http::get('/v1/project/variables/:variableId')
->desc('Get Variable')
->groups(['api'])
->label('scope', 'projects.read')
@@ -224,7 +224,7 @@ App::get('/v1/project/variables/:variableId')
$response->dynamic($variable, Response::MODEL_VARIABLE);
});
App::put('/v1/project/variables/:variableId')
Http::put('/v1/project/variables/:variableId')
->desc('Update Variable')
->groups(['api'])
->label('scope', 'projects.write')
@@ -270,7 +270,7 @@ App::put('/v1/project/variables/:variableId')
$response->dynamic($variable, Response::MODEL_VARIABLE);
});
App::delete('/v1/project/variables/:variableId')
Http::delete('/v1/project/variables/:variableId')
->desc('Delete Variable')
->groups(['api'])
->label('scope', 'projects.write')
+52 -52
View File
@@ -12,7 +12,7 @@ use Appwrite\Utopia\Database\Validator\Queries\Projects;
use Appwrite\Utopia\Response;
use PHPMailer\PHPMailer\PHPMailer;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Audit\Audit;
use Utopia\Cache\Cache;
use Utopia\Config\Config;
@@ -30,16 +30,16 @@ use Utopia\Database\Validator\UID;
use Utopia\Locale\Locale;
use Utopia\Pools\Group;
use Utopia\Registry\Registry;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Boolean;
use Utopia\Validator\Hostname;
use Utopia\Validator\Integer;
use Utopia\Validator\Range;
use Utopia\Validator\Text;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Boolean;
use Utopia\Http\Validator\Hostname;
use Utopia\Http\Validator\Integer;
use Utopia\Http\Validator\Range;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\URL;
use Utopia\Http\Validator\WhiteList;
App::init()
Http::init()
->groups(['projects'])
->inject('project')
->action(function (Document $project) {
@@ -48,7 +48,7 @@ App::init()
}
});
App::post('/v1/projects')
Http::post('/v1/projects')
->desc('Create project')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -61,7 +61,7 @@ App::post('/v1/projects')
->param('projectId', '', new ProjectId(), 'Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, and hyphen. Can\'t start with a special char. Max length is 36 chars.')
->param('name', null, new Text(128), 'Project name. Max length: 128 chars.')
->param('teamId', '', new UID(), 'Team unique ID.')
->param('region', App::getEnv('_APP_REGION', 'default'), new Whitelist(array_keys(array_filter(Config::getParam('regions'), fn ($config) => !$config['disabled']))), 'Project Region.', true)
->param('region', Http::getEnv('_APP_REGION', 'default'), new Whitelist(array_keys(array_filter(Config::getParam('regions'), fn ($config) => !$config['disabled']))), 'Project Region.', true)
->param('description', '', new Text(256), 'Project description. Max length: 256 chars.', true)
->param('logo', '', new Text(1024), 'Project logo.', true)
->param('url', '', new URL(), 'Project URL.', true)
@@ -219,7 +219,7 @@ App::post('/v1/projects')
->dynamic($project, Response::MODEL_PROJECT);
});
App::get('/v1/projects')
Http::get('/v1/projects')
->desc('List projects')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -266,7 +266,7 @@ App::get('/v1/projects')
]), Response::MODEL_PROJECT_LIST);
});
App::get('/v1/projects/:projectId')
Http::get('/v1/projects/:projectId')
->desc('Get project')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -290,7 +290,7 @@ App::get('/v1/projects/:projectId')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::get('/v1/projects/:projectId/usage')
Http::get('/v1/projects/:projectId/usage')
->desc('Get usage stats for a project')
->groups(['api', 'projects', 'usage'])
->label('scope', 'projects.read')
@@ -315,7 +315,7 @@ App::get('/v1/projects/:projectId/usage')
}
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -404,7 +404,7 @@ App::get('/v1/projects/:projectId/usage')
$response->dynamic($usage, Response::MODEL_USAGE_PROJECT);
});
App::patch('/v1/projects/:projectId')
Http::patch('/v1/projects/:projectId')
->desc('Update project')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -451,7 +451,7 @@ App::patch('/v1/projects/:projectId')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/team')
Http::patch('/v1/projects/:projectId/team')
->desc('Update Project Team')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -491,7 +491,7 @@ App::patch('/v1/projects/:projectId/team')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/service')
Http::patch('/v1/projects/:projectId/service')
->desc('Update service status')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -522,7 +522,7 @@ App::patch('/v1/projects/:projectId/service')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/service/all')
Http::patch('/v1/projects/:projectId/service/all')
->desc('Update all service status')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -556,7 +556,7 @@ App::patch('/v1/projects/:projectId/service/all')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/oauth2')
Http::patch('/v1/projects/:projectId/oauth2')
->desc('Update project OAuth2')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -600,7 +600,7 @@ App::patch('/v1/projects/:projectId/oauth2')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/limit')
Http::patch('/v1/projects/:projectId/auth/limit')
->desc('Update project users limit')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -631,7 +631,7 @@ App::patch('/v1/projects/:projectId/auth/limit')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/duration')
Http::patch('/v1/projects/:projectId/auth/duration')
->desc('Update project authentication duration')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -662,7 +662,7 @@ App::patch('/v1/projects/:projectId/auth/duration')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/:method')
Http::patch('/v1/projects/:projectId/auth/:method')
->desc('Update project auth method status. Use this endpoint to enable or disable a given auth method for this project.')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -696,7 +696,7 @@ App::patch('/v1/projects/:projectId/auth/:method')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/password-history')
Http::patch('/v1/projects/:projectId/auth/password-history')
->desc('Update authentication password history. Use this endpoint to set the number of password history to save and 0 to disable password history.')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -727,7 +727,7 @@ App::patch('/v1/projects/:projectId/auth/password-history')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/password-dictionary')
Http::patch('/v1/projects/:projectId/auth/password-dictionary')
->desc('Update authentication password dictionary status. Use this endpoint to enable or disable the dicitonary check for user password')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -758,7 +758,7 @@ App::patch('/v1/projects/:projectId/auth/password-dictionary')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/personal-data')
Http::patch('/v1/projects/:projectId/auth/personal-data')
->desc('Enable or disable checking user passwords for similarity with their personal data.')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -789,7 +789,7 @@ App::patch('/v1/projects/:projectId/auth/personal-data')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::patch('/v1/projects/:projectId/auth/max-sessions')
Http::patch('/v1/projects/:projectId/auth/max-sessions')
->desc('Update project user sessions limit')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -820,7 +820,7 @@ App::patch('/v1/projects/:projectId/auth/max-sessions')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::delete('/v1/projects/:projectId')
Http::delete('/v1/projects/:projectId')
->desc('Delete project')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -854,7 +854,7 @@ App::delete('/v1/projects/:projectId')
// Webhooks
App::post('/v1/projects/:projectId/webhooks')
Http::post('/v1/projects/:projectId/webhooks')
->desc('Create webhook')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -910,7 +910,7 @@ App::post('/v1/projects/:projectId/webhooks')
->dynamic($webhook, Response::MODEL_WEBHOOK);
});
App::get('/v1/projects/:projectId/webhooks')
Http::get('/v1/projects/:projectId/webhooks')
->desc('List webhooks')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -942,7 +942,7 @@ App::get('/v1/projects/:projectId/webhooks')
]), Response::MODEL_WEBHOOK_LIST);
});
App::get('/v1/projects/:projectId/webhooks/:webhookId')
Http::get('/v1/projects/:projectId/webhooks/:webhookId')
->desc('Get webhook')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -976,7 +976,7 @@ App::get('/v1/projects/:projectId/webhooks/:webhookId')
$response->dynamic($webhook, Response::MODEL_WEBHOOK);
});
App::put('/v1/projects/:projectId/webhooks/:webhookId')
Http::put('/v1/projects/:projectId/webhooks/:webhookId')
->desc('Update webhook')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1029,7 +1029,7 @@ App::put('/v1/projects/:projectId/webhooks/:webhookId')
$response->dynamic($webhook, Response::MODEL_WEBHOOK);
});
App::patch('/v1/projects/:projectId/webhooks/:webhookId/signature')
Http::patch('/v1/projects/:projectId/webhooks/:webhookId/signature')
->desc('Update webhook signature key')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1068,7 +1068,7 @@ App::patch('/v1/projects/:projectId/webhooks/:webhookId/signature')
$response->dynamic($webhook, Response::MODEL_WEBHOOK);
});
App::delete('/v1/projects/:projectId/webhooks/:webhookId')
Http::delete('/v1/projects/:projectId/webhooks/:webhookId')
->desc('Delete webhook')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1107,7 +1107,7 @@ App::delete('/v1/projects/:projectId/webhooks/:webhookId')
// Keys
App::post('/v1/projects/:projectId/keys')
Http::post('/v1/projects/:projectId/keys')
->desc('Create key')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1157,7 +1157,7 @@ App::post('/v1/projects/:projectId/keys')
->dynamic($key, Response::MODEL_KEY);
});
App::get('/v1/projects/:projectId/keys')
Http::get('/v1/projects/:projectId/keys')
->desc('List keys')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -1189,7 +1189,7 @@ App::get('/v1/projects/:projectId/keys')
]), Response::MODEL_KEY_LIST);
});
App::get('/v1/projects/:projectId/keys/:keyId')
Http::get('/v1/projects/:projectId/keys/:keyId')
->desc('Get key')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -1223,7 +1223,7 @@ App::get('/v1/projects/:projectId/keys/:keyId')
$response->dynamic($key, Response::MODEL_KEY);
});
App::put('/v1/projects/:projectId/keys/:keyId')
Http::put('/v1/projects/:projectId/keys/:keyId')
->desc('Update key')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1269,7 +1269,7 @@ App::put('/v1/projects/:projectId/keys/:keyId')
$response->dynamic($key, Response::MODEL_KEY);
});
App::delete('/v1/projects/:projectId/keys/:keyId')
Http::delete('/v1/projects/:projectId/keys/:keyId')
->desc('Delete key')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1308,7 +1308,7 @@ App::delete('/v1/projects/:projectId/keys/:keyId')
// Platforms
App::post('/v1/projects/:projectId/platforms')
Http::post('/v1/projects/:projectId/platforms')
->desc('Create platform')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1358,7 +1358,7 @@ App::post('/v1/projects/:projectId/platforms')
->dynamic($platform, Response::MODEL_PLATFORM);
});
App::get('/v1/projects/:projectId/platforms')
Http::get('/v1/projects/:projectId/platforms')
->desc('List platforms')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -1390,7 +1390,7 @@ App::get('/v1/projects/:projectId/platforms')
]), Response::MODEL_PLATFORM_LIST);
});
App::get('/v1/projects/:projectId/platforms/:platformId')
Http::get('/v1/projects/:projectId/platforms/:platformId')
->desc('Get platform')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
@@ -1424,7 +1424,7 @@ App::get('/v1/projects/:projectId/platforms/:platformId')
$response->dynamic($platform, Response::MODEL_PLATFORM);
});
App::put('/v1/projects/:projectId/platforms/:platformId')
Http::put('/v1/projects/:projectId/platforms/:platformId')
->desc('Update platform')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1471,7 +1471,7 @@ App::put('/v1/projects/:projectId/platforms/:platformId')
$response->dynamic($platform, Response::MODEL_PLATFORM);
});
App::delete('/v1/projects/:projectId/platforms/:platformId')
Http::delete('/v1/projects/:projectId/platforms/:platformId')
->desc('Delete platform')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1510,7 +1510,7 @@ App::delete('/v1/projects/:projectId/platforms/:platformId')
// CUSTOM SMTP and Templates
App::patch('/v1/projects/:projectId/smtp')
Http::patch('/v1/projects/:projectId/smtp')
->desc('Update SMTP configuration')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1600,7 +1600,7 @@ App::patch('/v1/projects/:projectId/smtp')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::get('/v1/projects/:projectId/templates/sms/:type/:locale')
Http::get('/v1/projects/:projectId/templates/sms/:type/:locale')
->desc('Get custom SMS template')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1641,7 +1641,7 @@ App::get('/v1/projects/:projectId/templates/sms/:type/:locale')
});
App::get('/v1/projects/:projectId/templates/email/:type/:locale')
Http::get('/v1/projects/:projectId/templates/email/:type/:locale')
->desc('Get custom email template')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1694,7 +1694,7 @@ App::get('/v1/projects/:projectId/templates/email/:type/:locale')
$response->dynamic(new Document($template), Response::MODEL_EMAIL_TEMPLATE);
});
App::patch('/v1/projects/:projectId/templates/sms/:type/:locale')
Http::patch('/v1/projects/:projectId/templates/sms/:type/:locale')
->desc('Update custom SMS template')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1734,7 +1734,7 @@ App::patch('/v1/projects/:projectId/templates/sms/:type/:locale')
]), Response::MODEL_SMS_TEMPLATE);
});
App::patch('/v1/projects/:projectId/templates/email/:type/:locale')
Http::patch('/v1/projects/:projectId/templates/email/:type/:locale')
->desc('Update custom email templates')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1784,7 +1784,7 @@ App::patch('/v1/projects/:projectId/templates/email/:type/:locale')
]), Response::MODEL_EMAIL_TEMPLATE);
});
App::delete('/v1/projects/:projectId/templates/sms/:type/:locale')
Http::delete('/v1/projects/:projectId/templates/sms/:type/:locale')
->desc('Reset custom SMS template')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
@@ -1827,7 +1827,7 @@ App::delete('/v1/projects/:projectId/templates/sms/:type/:locale')
]), Response::MODEL_SMS_TEMPLATE);
});
App::delete('/v1/projects/:projectId/templates/email/:type/:locale')
Http::delete('/v1/projects/:projectId/templates/email/:type/:locale')
->desc('Reset custom email template')
->groups(['api', 'projects'])
->label('scope', 'projects.write')
+13 -13
View File
@@ -7,18 +7,18 @@ use Appwrite\Extend\Exception;
use Appwrite\Network\Validator\CNAME;
use Appwrite\Utopia\Database\Validator\Queries\Rules;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Query;
use Utopia\Database\Validator\UID;
use Utopia\Domains\Domain;
use Utopia\Validator\Domain as ValidatorDomain;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\Domain as ValidatorDomain;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\WhiteList;
App::post('/v1/proxy/rules')
Http::post('/v1/proxy/rules')
->groups(['api', 'proxy'])
->desc('Create Rule')
->label('scope', 'rules.write')
@@ -41,7 +41,7 @@ App::post('/v1/proxy/rules')
->inject('dbForConsole')
->inject('dbForProject')
->action(function (string $domain, string $resourceType, string $resourceId, Response $response, Document $project, Event $events, Database $dbForConsole, Database $dbForProject) {
$mainDomain = App::getEnv('_APP_DOMAIN', '');
$mainDomain = Http::getEnv('_APP_DOMAIN', '');
if ($domain === $mainDomain) {
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'You cannot assign your main domain to specific resource. Please use subdomain or a different domain.');
}
@@ -101,13 +101,13 @@ App::post('/v1/proxy/rules')
]);
$status = 'created';
$functionsDomain = App::getEnv('_APP_DOMAIN_FUNCTIONS');
$functionsDomain = Http::getEnv('_APP_DOMAIN_FUNCTIONS');
if (!empty($functionsDomain) && \str_ends_with($domain->get(), $functionsDomain)) {
$status = 'verified';
}
if ($status === 'created') {
$target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));
$target = new Domain(Http::getEnv('_APP_DOMAIN_TARGET', ''));
$validator = new CNAME($target->get()); // Verify Domain with DNS records
if ($validator->isValid($domain->get())) {
@@ -134,7 +134,7 @@ App::post('/v1/proxy/rules')
->dynamic($rule, Response::MODEL_PROXY_RULE);
});
App::get('/v1/proxy/rules')
Http::get('/v1/proxy/rules')
->groups(['api', 'proxy'])
->desc('List Rules')
->label('scope', 'rules.read')
@@ -189,7 +189,7 @@ App::get('/v1/proxy/rules')
]), Response::MODEL_PROXY_RULE_LIST);
});
App::get('/v1/proxy/rules/:ruleId')
Http::get('/v1/proxy/rules/:ruleId')
->groups(['api', 'proxy'])
->desc('Get Rule')
->label('scope', 'rules.read')
@@ -218,7 +218,7 @@ App::get('/v1/proxy/rules/:ruleId')
$response->dynamic($rule, Response::MODEL_PROXY_RULE);
});
App::delete('/v1/proxy/rules/:ruleId')
Http::delete('/v1/proxy/rules/:ruleId')
->groups(['api', 'proxy'])
->desc('Delete Rule')
->label('scope', 'rules.write')
@@ -255,7 +255,7 @@ App::delete('/v1/proxy/rules/:ruleId')
$response->noContent();
});
App::patch('/v1/proxy/rules/:ruleId/verification')
Http::patch('/v1/proxy/rules/:ruleId/verification')
->desc('Update Rule Verification Status')
->groups(['api', 'proxy'])
->label('scope', 'rules.write')
@@ -280,7 +280,7 @@ App::patch('/v1/proxy/rules/:ruleId/verification')
throw new Exception(Exception::RULE_NOT_FOUND);
}
$target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));
$target = new Domain(Http::getEnv('_APP_DOMAIN_TARGET', ''));
if (!$target->isKnown() || $target->isTest()) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Domain target must be configured as environment variable.');
+36 -36
View File
@@ -8,7 +8,7 @@ use Appwrite\Event\Event;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\OpenSSL\OpenSSL;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\Document;
@@ -36,16 +36,16 @@ use Utopia\Storage\Validator\File;
use Utopia\Storage\Validator\FileExt;
use Utopia\Storage\Validator\FileSize;
use Utopia\Storage\Validator\Upload;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Boolean;
use Utopia\Validator\HexColor;
use Utopia\Validator\Range;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Boolean;
use Utopia\Http\Validator\HexColor;
use Utopia\Http\Validator\Range;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\WhiteList;
use Utopia\DSN\DSN;
use Utopia\Swoole\Request;
App::post('/v1/storage/buckets')
Http::post('/v1/storage/buckets')
->desc('Create bucket')
->groups(['api', 'storage'])
->label('scope', 'buckets.write')
@@ -65,7 +65,7 @@ App::post('/v1/storage/buckets')
->param('permissions', null, new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of permission strings. By default, no user is granted with any permissions. [Learn more about permissions](/docs/permissions).', true)
->param('fileSecurity', false, new Boolean(true), 'Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](/docs/permissions).', true)
->param('enabled', true, new Boolean(true), 'Is bucket enabled? When set to \'disabled\', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled.', true)
->param('maximumFileSize', (int) App::getEnv('_APP_STORAGE_LIMIT', 0), new Range(1, (int) App::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is ' . Storage::human(App::getEnv('_APP_STORAGE_LIMIT', 0), 0) . '.', true)
->param('maximumFileSize', (int) Http::getEnv('_APP_STORAGE_LIMIT', 0), new Range(1, (int) Http::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is ' . Storage::human(Http::getEnv('_APP_STORAGE_LIMIT', 0), 0) . '.', true)
->param('allowedFileExtensions', [], new ArrayList(new Text(64), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Allowed file extensions. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' extensions are allowed, each 64 characters long.', true)
->param('compression', COMPRESSION_TYPE_NONE, new WhiteList([COMPRESSION_TYPE_NONE, COMPRESSION_TYPE_GZIP, COMPRESSION_TYPE_ZSTD]), 'Compression algorithm choosen for compression. Can be one of ' . COMPRESSION_TYPE_NONE . ', [' . COMPRESSION_TYPE_GZIP . '](https://en.wikipedia.org/wiki/Gzip), or [' . COMPRESSION_TYPE_ZSTD . '](https://en.wikipedia.org/wiki/Zstd), For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' compression is skipped even if it\'s enabled', true)
->param('encryption', true, new Boolean(true), 'Is encryption enabled? For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' encryption is skipped even if it\'s enabled', true)
@@ -144,7 +144,7 @@ App::post('/v1/storage/buckets')
->dynamic($bucket, Response::MODEL_BUCKET);
});
App::get('/v1/storage/buckets')
Http::get('/v1/storage/buckets')
->desc('List buckets')
->groups(['api', 'storage'])
->label('scope', 'buckets.read')
@@ -193,7 +193,7 @@ App::get('/v1/storage/buckets')
]), Response::MODEL_BUCKET_LIST);
});
App::get('/v1/storage/buckets/:bucketId')
Http::get('/v1/storage/buckets/:bucketId')
->desc('Get bucket')
->groups(['api', 'storage'])
->label('scope', 'buckets.read')
@@ -219,7 +219,7 @@ App::get('/v1/storage/buckets/:bucketId')
$response->dynamic($bucket, Response::MODEL_BUCKET);
});
App::put('/v1/storage/buckets/:bucketId')
Http::put('/v1/storage/buckets/:bucketId')
->desc('Update bucket')
->groups(['api', 'storage'])
->label('scope', 'buckets.write')
@@ -239,7 +239,7 @@ App::put('/v1/storage/buckets/:bucketId')
->param('permissions', null, new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](/docs/permissions).', true)
->param('fileSecurity', false, new Boolean(true), 'Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](/docs/permissions).', true)
->param('enabled', true, new Boolean(true), 'Is bucket enabled? When set to \'disabled\', users cannot access the files in this bucket but Server SDKs with and API key can still access the bucket. No files are lost when this is toggled.', true)
->param('maximumFileSize', null, new Range(1, (int) App::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is ' . Storage::human((int)App::getEnv('_APP_STORAGE_LIMIT', 0), 0) . '.', true)
->param('maximumFileSize', null, new Range(1, (int) Http::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is ' . Storage::human((int)Http::getEnv('_APP_STORAGE_LIMIT', 0), 0) . '.', true)
->param('allowedFileExtensions', [], new ArrayList(new Text(64), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Allowed file extensions. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' extensions are allowed, each 64 characters long.', true)
->param('compression', COMPRESSION_TYPE_NONE, new WhiteList([COMPRESSION_TYPE_NONE, COMPRESSION_TYPE_GZIP, COMPRESSION_TYPE_ZSTD]), 'Compression algorithm choosen for compression. Can be one of ' . COMPRESSION_TYPE_NONE . ', [' . COMPRESSION_TYPE_GZIP . '](https://en.wikipedia.org/wiki/Gzip), or [' . COMPRESSION_TYPE_ZSTD . '](https://en.wikipedia.org/wiki/Zstd), For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' compression is skipped even if it\'s enabled', true)
->param('encryption', true, new Boolean(true), 'Is encryption enabled? For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' encryption is skipped even if it\'s enabled', true)
@@ -255,7 +255,7 @@ App::put('/v1/storage/buckets/:bucketId')
}
$permissions ??= $bucket->getPermissions();
$maximumFileSize ??= $bucket->getAttribute('maximumFileSize', (int) App::getEnv('_APP_STORAGE_LIMIT', 0));
$maximumFileSize ??= $bucket->getAttribute('maximumFileSize', (int) Http::getEnv('_APP_STORAGE_LIMIT', 0));
$allowedFileExtensions ??= $bucket->getAttribute('allowedFileExtensions', []);
$enabled ??= $bucket->getAttribute('enabled', true);
$encryption ??= $bucket->getAttribute('encryption', true);
@@ -287,7 +287,7 @@ App::put('/v1/storage/buckets/:bucketId')
$response->dynamic($bucket, Response::MODEL_BUCKET);
});
App::delete('/v1/storage/buckets/:bucketId')
Http::delete('/v1/storage/buckets/:bucketId')
->desc('Delete bucket')
->groups(['api', 'storage'])
->label('scope', 'buckets.write')
@@ -329,7 +329,7 @@ App::delete('/v1/storage/buckets/:bucketId')
$response->noContent();
});
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->alias('/v1/storage/files', ['bucketId' => 'default'])
->desc('Create file')
->groups(['api', 'storage'])
@@ -419,7 +419,7 @@ App::post('/v1/storage/buckets/:bucketId/files')
}
$maximumFileSize = $bucket->getAttribute('maximumFileSize', 0);
if ($maximumFileSize > (int) App::getEnv('_APP_STORAGE_LIMIT', 0)) {
if ($maximumFileSize > (int) Http::getEnv('_APP_STORAGE_LIMIT', 0)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Maximum bucket file size is larger than _APP_STORAGE_LIMIT');
}
@@ -521,10 +521,10 @@ App::post('/v1/storage/buckets/:bucketId/files')
}
if ($chunksUploaded === $chunks) {
if (App::getEnv('_APP_STORAGE_ANTIVIRUS') === 'enabled' && $bucket->getAttribute('antivirus', true) && $fileSize <= APP_LIMIT_ANTIVIRUS && $deviceFiles->getType() === Storage::DEVICE_LOCAL) {
if (Http::getEnv('_APP_STORAGE_ANTIVIRUS') === 'enabled' && $bucket->getAttribute('antivirus', true) && $fileSize <= APP_LIMIT_ANTIVIRUS && $deviceFiles->getType() === Storage::DEVICE_LOCAL) {
$antivirus = new Network(
App::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),
(int) App::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)
Http::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),
(int) Http::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)
);
if (!$antivirus->fileScan($path)) {
@@ -556,7 +556,7 @@ App::post('/v1/storage/buckets/:bucketId/files')
if (empty($data)) {
$data = $deviceFiles->read($path);
}
$key = App::getEnv('_APP_OPENSSL_KEY_V1');
$key = Http::getEnv('_APP_OPENSSL_KEY_V1');
$iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM));
$data = OpenSSL::encrypt($data, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag);
}
@@ -682,7 +682,7 @@ App::post('/v1/storage/buckets/:bucketId/files')
->dynamic($file, Response::MODEL_FILE);
});
App::get('/v1/storage/buckets/:bucketId/files')
Http::get('/v1/storage/buckets/:bucketId/files')
->alias('/v1/storage/files', ['bucketId' => 'default'])
->desc('List files')
->groups(['api', 'storage'])
@@ -763,7 +763,7 @@ App::get('/v1/storage/buckets/:bucketId/files')
]), Response::MODEL_FILE_LIST);
});
App::get('/v1/storage/buckets/:bucketId/files/:fileId')
Http::get('/v1/storage/buckets/:bucketId/files/:fileId')
->alias('/v1/storage/files/:fileId', ['bucketId' => 'default'])
->desc('Get file')
->groups(['api', 'storage'])
@@ -812,7 +812,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId')
$response->dynamic($file, Response::MODEL_FILE);
});
App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
Http::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
->alias('/v1/storage/files/:fileId/preview', ['bucketId' => 'default'])
->desc('Get file preview')
->groups(['api', 'storage'])
@@ -894,7 +894,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
$algorithm = $file->getAttribute('algorithm', 'none');
$cipher = $file->getAttribute('openSSLCipher');
$mime = $file->getAttribute('mimeType');
if (!\in_array($mime, $inputs) || $file->getAttribute('sizeActual') > (int) App::getEnv('_APP_STORAGE_PREVIEW_LIMIT', 20000000)) {
if (!\in_array($mime, $inputs) || $file->getAttribute('sizeActual') > (int) Http::getEnv('_APP_STORAGE_PREVIEW_LIMIT', 20000000)) {
if (!\in_array($mime, $inputs)) {
$path = (\array_key_exists($mime, $fileLogos)) ? $fileLogos[$mime] : $fileLogos['default'];
} else {
@@ -926,7 +926,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
$source = OpenSSL::decrypt(
$source,
$file->getAttribute('openSSLCipher'),
App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),
Http::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),
0,
\hex2bin($file->getAttribute('openSSLIV')),
\hex2bin($file->getAttribute('openSSLTag'))
@@ -981,7 +981,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
unset($image);
});
App::get('/v1/storage/buckets/:bucketId/files/:fileId/download')
Http::get('/v1/storage/buckets/:bucketId/files/:fileId/download')
->alias('/v1/storage/files/:fileId/download', ['bucketId' => 'default'])
->desc('Get file for download')
->groups(['api', 'storage'])
@@ -1072,7 +1072,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/download')
$source = OpenSSL::decrypt(
$source,
$file->getAttribute('openSSLCipher'),
App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),
Http::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),
0,
\hex2bin($file->getAttribute('openSSLIV')),
\hex2bin($file->getAttribute('openSSLTag'))
@@ -1124,7 +1124,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/download')
}
});
App::get('/v1/storage/buckets/:bucketId/files/:fileId/view')
Http::get('/v1/storage/buckets/:bucketId/files/:fileId/view')
->alias('/v1/storage/files/:fileId/view', ['bucketId' => 'default'])
->desc('Get file for view')
->groups(['api', 'storage'])
@@ -1224,7 +1224,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view')
$source = OpenSSL::decrypt(
$source,
$file->getAttribute('openSSLCipher'),
App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),
Http::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')),
0,
\hex2bin($file->getAttribute('openSSLIV')),
\hex2bin($file->getAttribute('openSSLTag'))
@@ -1277,7 +1277,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view')
}
});
App::put('/v1/storage/buckets/:bucketId/files/:fileId')
Http::put('/v1/storage/buckets/:bucketId/files/:fileId')
->alias('/v1/storage/files/:fileId', ['bucketId' => 'default'])
->desc('Update file')
->groups(['api', 'storage'])
@@ -1387,7 +1387,7 @@ App::put('/v1/storage/buckets/:bucketId/files/:fileId')
$response->dynamic($file, Response::MODEL_FILE);
});
App::delete('/v1/storage/buckets/:bucketId/files/:fileId')
Http::delete('/v1/storage/buckets/:bucketId/files/:fileId')
->desc('Delete File')
->groups(['api', 'storage'])
->label('scope', 'files.write')
@@ -1485,7 +1485,7 @@ App::delete('/v1/storage/buckets/:bucketId/files/:fileId')
$response->noContent();
});
App::get('/v1/storage/usage')
Http::get('/v1/storage/usage')
->desc('Get usage stats for storage')
->groups(['api', 'storage', 'usage'])
->label('scope', 'files.read')
@@ -1501,7 +1501,7 @@ App::get('/v1/storage/usage')
->action(function (string $range, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
@@ -1595,7 +1595,7 @@ App::get('/v1/storage/usage')
$response->dynamic($usage, Response::MODEL_USAGE_STORAGE);
});
App::get('/v1/storage/:bucketId/usage')
Http::get('/v1/storage/:bucketId/usage')
->desc('Get usage stats for a storage bucket')
->groups(['api', 'storage', 'usage'])
->label('scope', 'files.read')
@@ -1618,7 +1618,7 @@ App::get('/v1/storage/:bucketId/usage')
}
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
+22 -22
View File
@@ -9,7 +9,7 @@ use Appwrite\Event\Mail;
use Appwrite\Event\Phone as EventPhone;
use Appwrite\Extend\Exception;
use Appwrite\Network\Validator\Email;
use Utopia\Validator\Host;
use Utopia\Http\Validator\Host;
use Appwrite\Template\Template;
use Appwrite\Utopia\Database\Validator\CustomId;
use Utopia\Database\Validator\Queries;
@@ -20,7 +20,7 @@ use Utopia\Database\Validator\Query\Offset;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use MaxMind\Db\Reader;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Audit\Audit;
use Utopia\Config\Config;
use Utopia\Database\Database;
@@ -36,11 +36,11 @@ use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Key;
use Utopia\Database\Validator\UID;
use Utopia\Locale\Locale;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Assoc;
use Utopia\Validator\Text;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Assoc;
use Utopia\Http\Validator\Text;
App::post('/v1/teams')
Http::post('/v1/teams')
->desc('Create team')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].create')
@@ -128,7 +128,7 @@ App::post('/v1/teams')
->dynamic($team, Response::MODEL_TEAM);
});
App::get('/v1/teams')
Http::get('/v1/teams')
->desc('List teams')
->groups(['api', 'teams'])
->label('scope', 'teams.read')
@@ -180,7 +180,7 @@ App::get('/v1/teams')
]), Response::MODEL_TEAM_LIST);
});
App::get('/v1/teams/:teamId')
Http::get('/v1/teams/:teamId')
->desc('Get team')
->groups(['api', 'teams'])
->label('scope', 'teams.read')
@@ -207,7 +207,7 @@ App::get('/v1/teams/:teamId')
$response->dynamic($team, Response::MODEL_TEAM);
});
App::get('/v1/teams/:teamId/prefs')
Http::get('/v1/teams/:teamId/prefs')
->desc('Get team preferences')
->groups(['api', 'teams'])
->label('scope', 'teams.read')
@@ -235,7 +235,7 @@ App::get('/v1/teams/:teamId/prefs')
$response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES);
});
App::put('/v1/teams/:teamId')
Http::put('/v1/teams/:teamId')
->desc('Update name')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].update')
@@ -278,7 +278,7 @@ App::put('/v1/teams/:teamId')
$response->dynamic($team, Response::MODEL_TEAM);
});
App::put('/v1/teams/:teamId/prefs')
Http::put('/v1/teams/:teamId/prefs')
->desc('Update preferences')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].update.prefs')
@@ -314,7 +314,7 @@ App::put('/v1/teams/:teamId/prefs')
$response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES);
});
App::delete('/v1/teams/:teamId')
Http::delete('/v1/teams/:teamId')
->desc('Delete team')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].delete')
@@ -356,7 +356,7 @@ App::delete('/v1/teams/:teamId')
$response->noContent();
});
App::post('/v1/teams/:teamId/memberships')
Http::post('/v1/teams/:teamId/memberships')
->desc('Create team membership')
->groups(['api', 'teams', 'auth'])
->label('event', 'teams.[teamId].memberships.[membershipId].create')
@@ -404,7 +404,7 @@ App::post('/v1/teams/:teamId/memberships')
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
$isAppUser = Auth::isAppUser(Authorization::getRoles());
if (!$isPrivilegedUser && !$isAppUser && empty(App::getEnv('_APP_SMTP_HOST'))) {
if (!$isPrivilegedUser && !$isAppUser && empty(Http::getEnv('_APP_SMTP_HOST'))) {
throw new Exception(Exception::GENERAL_SMTP_DISABLED);
}
@@ -561,8 +561,8 @@ App::post('/v1/teams/:teamId/memberships')
$smtp = $project->getAttribute('smtp', []);
$smtpEnabled = $smtp['enabled'] ?? false;
$senderEmail = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$senderEmail = Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$senderName = Http::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server');
$replyTo = "";
if ($smtpEnabled) {
@@ -665,7 +665,7 @@ App::post('/v1/teams/:teamId/memberships')
);
});
App::get('/v1/teams/:teamId/memberships')
Http::get('/v1/teams/:teamId/memberships')
->desc('List team memberships')
->groups(['api', 'teams'])
->label('scope', 'teams.read')
@@ -749,7 +749,7 @@ App::get('/v1/teams/:teamId/memberships')
]), Response::MODEL_MEMBERSHIP_LIST);
});
App::get('/v1/teams/:teamId/memberships/:membershipId')
Http::get('/v1/teams/:teamId/memberships/:membershipId')
->desc('Get team membership')
->groups(['api', 'teams'])
->label('scope', 'teams.read')
@@ -791,7 +791,7 @@ App::get('/v1/teams/:teamId/memberships/:membershipId')
$response->dynamic($membership, Response::MODEL_MEMBERSHIP);
});
App::patch('/v1/teams/:teamId/memberships/:membershipId')
Http::patch('/v1/teams/:teamId/memberships/:membershipId')
->desc('Update membership')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].memberships.[membershipId].update')
@@ -862,7 +862,7 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId')
);
});
App::patch('/v1/teams/:teamId/memberships/:membershipId/status')
Http::patch('/v1/teams/:teamId/memberships/:membershipId/status')
->desc('Update team membership status')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].memberships.[membershipId].update.status')
@@ -997,7 +997,7 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId/status')
);
});
App::delete('/v1/teams/:teamId/memberships/:membershipId')
Http::delete('/v1/teams/:teamId/memberships/:membershipId')
->desc('Delete team membership')
->groups(['api', 'teams'])
->label('event', 'teams.[teamId].memberships.[membershipId].delete')
@@ -1063,7 +1063,7 @@ App::delete('/v1/teams/:teamId/memberships/:membershipId')
$response->noContent();
});
App::get('/v1/teams/:teamId/logs')
Http::get('/v1/teams/:teamId/logs')
->desc('List team logs')
->groups(['api', 'teams'])
->label('scope', 'teams.read')
+37 -37
View File
@@ -14,7 +14,7 @@ use Appwrite\Utopia\Database\Validator\Queries\Users;
use Utopia\Database\Validator\Query\Limit;
use Utopia\Database\Validator\Query\Offset;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Audit\Audit;
use Utopia\Config\Config;
use Utopia\Database\Helpers\ID;
@@ -29,13 +29,13 @@ use Utopia\Database\Validator\UID;
use Utopia\Database\Database;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Assoc;
use Utopia\Validator\WhiteList;
use Utopia\Validator\Text;
use Utopia\Validator\Boolean;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Assoc;
use Utopia\Http\Validator\WhiteList;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\Boolean;
use MaxMind\Db\Reader;
use Utopia\Validator\Integer;
use Utopia\Http\Validator\Integer;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PersonalData;
@@ -107,7 +107,7 @@ function createUser(string $hash, mixed $hashOptions, string $userId, ?string $e
return $user;
}
App::post('/v1/users')
Http::post('/v1/users')
->desc('Create user')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -140,7 +140,7 @@ App::post('/v1/users')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/bcrypt')
Http::post('/v1/users/bcrypt')
->desc('Create user with bcrypt password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -171,7 +171,7 @@ App::post('/v1/users/bcrypt')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/md5')
Http::post('/v1/users/md5')
->desc('Create user with MD5 password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -202,7 +202,7 @@ App::post('/v1/users/md5')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/argon2')
Http::post('/v1/users/argon2')
->desc('Create user with Argon2 password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -233,7 +233,7 @@ App::post('/v1/users/argon2')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/sha')
Http::post('/v1/users/sha')
->desc('Create user with SHA password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -271,7 +271,7 @@ App::post('/v1/users/sha')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/phpass')
Http::post('/v1/users/phpass')
->desc('Create user with PHPass password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -302,7 +302,7 @@ App::post('/v1/users/phpass')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/scrypt')
Http::post('/v1/users/scrypt')
->desc('Create user with Scrypt password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -346,7 +346,7 @@ App::post('/v1/users/scrypt')
->dynamic($user, Response::MODEL_USER);
});
App::post('/v1/users/scrypt-modified')
Http::post('/v1/users/scrypt-modified')
->desc('Create user with Scrypt modified password')
->groups(['api', 'users'])
->label('event', 'users.[userId].create')
@@ -380,7 +380,7 @@ App::post('/v1/users/scrypt-modified')
->dynamic($user, Response::MODEL_USER);
});
App::get('/v1/users')
Http::get('/v1/users')
->desc('List users')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -429,7 +429,7 @@ App::get('/v1/users')
]), Response::MODEL_USER_LIST);
});
App::get('/v1/users/:userId')
Http::get('/v1/users/:userId')
->desc('Get user')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -455,7 +455,7 @@ App::get('/v1/users/:userId')
$response->dynamic($user, Response::MODEL_USER);
});
App::get('/v1/users/:userId/prefs')
Http::get('/v1/users/:userId/prefs')
->desc('Get user preferences')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -483,7 +483,7 @@ App::get('/v1/users/:userId/prefs')
$response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES);
});
App::get('/v1/users/:userId/sessions')
Http::get('/v1/users/:userId/sessions')
->desc('List user sessions')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -525,7 +525,7 @@ App::get('/v1/users/:userId/sessions')
]), Response::MODEL_SESSION_LIST);
});
App::get('/v1/users/:userId/memberships')
Http::get('/v1/users/:userId/memberships')
->desc('List user memberships')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -565,7 +565,7 @@ App::get('/v1/users/:userId/memberships')
]), Response::MODEL_MEMBERSHIP_LIST);
});
App::get('/v1/users/:userId/logs')
Http::get('/v1/users/:userId/logs')
->desc('List user logs')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -647,7 +647,7 @@ App::get('/v1/users/:userId/logs')
]), Response::MODEL_LOG_LIST);
});
App::get('/v1/users/identities')
Http::get('/v1/users/identities')
->desc('List Identities')
->groups(['api', 'users'])
->label('scope', 'users.read')
@@ -696,7 +696,7 @@ App::get('/v1/users/identities')
]), Response::MODEL_IDENTITY_LIST);
});
App::patch('/v1/users/:userId/status')
Http::patch('/v1/users/:userId/status')
->desc('Update user status')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.status')
@@ -733,7 +733,7 @@ App::patch('/v1/users/:userId/status')
$response->dynamic($user, Response::MODEL_USER);
});
App::put('/v1/users/:userId/labels')
Http::put('/v1/users/:userId/labels')
->desc('Update user labels')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.labels')
@@ -771,7 +771,7 @@ App::put('/v1/users/:userId/labels')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/verification/phone')
Http::patch('/v1/users/:userId/verification/phone')
->desc('Update phone verification')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.verification')
@@ -807,7 +807,7 @@ App::patch('/v1/users/:userId/verification/phone')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/name')
Http::patch('/v1/users/:userId/name')
->desc('Update name')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.name')
@@ -845,7 +845,7 @@ App::patch('/v1/users/:userId/name')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/password')
Http::patch('/v1/users/:userId/password')
->desc('Update password')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.password')
@@ -910,7 +910,7 @@ App::patch('/v1/users/:userId/password')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/email')
Http::patch('/v1/users/:userId/email')
->desc('Update email')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.email')
@@ -967,7 +967,7 @@ App::patch('/v1/users/:userId/email')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/phone')
Http::patch('/v1/users/:userId/phone')
->desc('Update phone')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.phone')
@@ -1011,7 +1011,7 @@ App::patch('/v1/users/:userId/phone')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/verification')
Http::patch('/v1/users/:userId/verification')
->desc('Update email verification')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.verification')
@@ -1047,7 +1047,7 @@ App::patch('/v1/users/:userId/verification')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/prefs')
Http::patch('/v1/users/:userId/prefs')
->desc('Update user preferences')
->groups(['api', 'users'])
->label('event', 'users.[userId].update.prefs')
@@ -1081,7 +1081,7 @@ App::patch('/v1/users/:userId/prefs')
$response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES);
});
App::delete('/v1/users/:userId/sessions/:sessionId')
Http::delete('/v1/users/:userId/sessions/:sessionId')
->desc('Delete user session')
->groups(['api', 'users'])
->label('event', 'users.[userId].sessions.[sessionId].delete')
@@ -1125,7 +1125,7 @@ App::delete('/v1/users/:userId/sessions/:sessionId')
$response->noContent();
});
App::delete('/v1/users/:userId/sessions')
Http::delete('/v1/users/:userId/sessions')
->desc('Delete user sessions')
->groups(['api', 'users'])
->label('event', 'users.[userId].sessions.[sessionId].delete')
@@ -1168,7 +1168,7 @@ App::delete('/v1/users/:userId/sessions')
$response->noContent();
});
App::delete('/v1/users/:userId')
Http::delete('/v1/users/:userId')
->desc('Delete user')
->groups(['api', 'users'])
->label('event', 'users.[userId].delete')
@@ -1211,7 +1211,7 @@ App::delete('/v1/users/:userId')
$response->noContent();
});
App::delete('/v1/users/identities/:identityId')
Http::delete('/v1/users/identities/:identityId')
->desc('Delete Identity')
->groups(['api', 'users'])
->label('event', 'users.[userId].identities.[identityId].delete')
@@ -1243,7 +1243,7 @@ App::delete('/v1/users/identities/:identityId')
return $response->noContent();
});
App::get('/v1/users/usage')
Http::get('/v1/users/usage')
->desc('Get usage stats for the users API')
->groups(['api', 'users', 'usage'])
->label('scope', 'users.read')
@@ -1261,7 +1261,7 @@ App::get('/v1/users/usage')
->action(function (string $range, string $provider, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '1h',
+36 -36
View File
@@ -1,15 +1,15 @@
<?php
use Appwrite\Auth\OAuth2\Github as OAuth2Github;
use Utopia\App;
use Utopia\Http\Http;
use Appwrite\Event\Build;
use Appwrite\Event\Delete;
use Utopia\Validator\Host;
use Utopia\Http\Validator\Host;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Text;
use Utopia\VCS\Adapter\Git\GitHub;
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Database\Validator\Queries\Installations;
@@ -35,7 +35,7 @@ use Utopia\Detector\Adapter\Python;
use Utopia\Detector\Adapter\Ruby;
use Utopia\Detector\Adapter\Swift;
use Utopia\Detector\Detector;
use Utopia\Validator\Boolean;
use Utopia\Http\Validator\Boolean;
use function Swoole\Coroutine\batch;
@@ -226,7 +226,7 @@ $createGitDeployments = function (GitHub $github, string $providerInstallationId
}
};
App::get('/v1/vcs/github/authorize')
Http::get('/v1/vcs/github/authorize')
->desc('Install GitHub App')
->groups(['api', 'vcs'])
->label('scope', 'vcs.read')
@@ -251,7 +251,7 @@ App::get('/v1/vcs/github/authorize')
'failure' => $failure,
]);
$appName = App::getEnv('_APP_VCS_GITHUB_APP_NAME');
$appName = Http::getEnv('_APP_VCS_GITHUB_APP_NAME');
if (empty($appName)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'GitHub App name is not configured. Please configure VCS (Version Control System) variables in .env file.');
@@ -268,7 +268,7 @@ App::get('/v1/vcs/github/authorize')
->redirect($url);
});
App::get('/v1/vcs/github/callback')
Http::get('/v1/vcs/github/callback')
->desc('Capture installation and authorization from GitHub App')
->groups(['api', 'vcs'])
->label('scope', 'public')
@@ -322,7 +322,7 @@ App::get('/v1/vcs/github/callback')
// OAuth Authroization
if (!empty($code)) {
$oauth2 = new OAuth2Github(App::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), App::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), "");
$oauth2 = new OAuth2Github(Http::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), Http::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), "");
$accessToken = $oauth2->getAccessToken($code) ?? '';
$refreshToken = $oauth2->getRefreshToken($code) ?? '';
$accessTokenExpiry = $oauth2->getAccessTokenExpiry($code) ?? '';
@@ -369,8 +369,8 @@ App::get('/v1/vcs/github/callback')
// Create / Update installation
if (!empty($providerInstallationId)) {
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$owner = $github->getOwnerName($providerInstallationId) ?? '';
@@ -428,7 +428,7 @@ App::get('/v1/vcs/github/callback')
->redirect($redirectSuccess);
});
App::post('/v1/vcs/github/installations/:installationId/providerRepositories/:providerRepositoryId/detection')
Http::post('/v1/vcs/github/installations/:installationId/providerRepositories/:providerRepositoryId/detection')
->desc('Detect runtime settings from source code')
->groups(['api', 'vcs'])
->label('scope', 'vcs.write')
@@ -454,8 +454,8 @@ App::post('/v1/vcs/github/installations/:installationId/providerRepositories/:pr
}
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$owner = $github->getOwnerName($providerInstallationId);
@@ -496,7 +496,7 @@ App::post('/v1/vcs/github/installations/:installationId/providerRepositories/:pr
$response->dynamic(new Document($detection), Response::MODEL_DETECTION);
});
App::get('/v1/vcs/github/installations/:installationId/providerRepositories')
Http::get('/v1/vcs/github/installations/:installationId/providerRepositories')
->desc('List Repositories')
->groups(['api', 'vcs'])
->label('scope', 'vcs.read')
@@ -525,8 +525,8 @@ App::get('/v1/vcs/github/installations/:installationId/providerRepositories')
}
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$page = 1;
@@ -590,7 +590,7 @@ App::get('/v1/vcs/github/installations/:installationId/providerRepositories')
]), Response::MODEL_PROVIDER_REPOSITORY_LIST);
});
App::post('/v1/vcs/github/installations/:installationId/providerRepositories')
Http::post('/v1/vcs/github/installations/:installationId/providerRepositories')
->desc('Create repository')
->groups(['api', 'vcs'])
->label('scope', 'vcs.write')
@@ -617,7 +617,7 @@ App::post('/v1/vcs/github/installations/:installationId/providerRepositories')
}
if ($installation->getAttribute('personal', false) === true) {
$oauth2 = new OAuth2Github(App::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), App::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), "");
$oauth2 = new OAuth2Github(Http::getEnv('_APP_VCS_GITHUB_CLIENT_ID', ''), Http::getEnv('_APP_VCS_GITHUB_CLIENT_SECRET', ''), "");
$identity = $dbForConsole->findOne('identities', [
Query::equal('provider', ['github']),
@@ -659,8 +659,8 @@ App::post('/v1/vcs/github/installations/:installationId/providerRepositories')
}
} else {
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$owner = $github->getOwnerName($providerInstallationId);
@@ -691,7 +691,7 @@ App::post('/v1/vcs/github/installations/:installationId/providerRepositories')
$response->dynamic(new Document($repository), Response::MODEL_PROVIDER_REPOSITORY);
});
App::get('/v1/vcs/github/installations/:installationId/providerRepositories/:providerRepositoryId')
Http::get('/v1/vcs/github/installations/:installationId/providerRepositories/:providerRepositoryId')
->desc('Get repository')
->groups(['api', 'vcs'])
->label('scope', 'vcs.read')
@@ -716,8 +716,8 @@ App::get('/v1/vcs/github/installations/:installationId/providerRepositories/:pro
}
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$owner = $github->getOwnerName($providerInstallationId) ?? '';
@@ -737,7 +737,7 @@ App::get('/v1/vcs/github/installations/:installationId/providerRepositories/:pro
$response->dynamic(new Document($repository), Response::MODEL_PROVIDER_REPOSITORY);
});
App::get('/v1/vcs/github/installations/:installationId/providerRepositories/:providerRepositoryId/branches')
Http::get('/v1/vcs/github/installations/:installationId/providerRepositories/:providerRepositoryId/branches')
->desc('List Repository Branches')
->groups(['api', 'vcs'])
->label('scope', 'vcs.read')
@@ -762,8 +762,8 @@ App::get('/v1/vcs/github/installations/:installationId/providerRepositories/:pro
}
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
$owner = $github->getOwnerName($providerInstallationId) ?? '';
@@ -783,7 +783,7 @@ App::get('/v1/vcs/github/installations/:installationId/providerRepositories/:pro
]), Response::MODEL_BRANCH_LIST);
});
App::post('/v1/vcs/github/events')
Http::post('/v1/vcs/github/events')
->desc('Create Event')
->groups(['api', 'vcs'])
->label('scope', 'public')
@@ -796,7 +796,7 @@ App::post('/v1/vcs/github/events')
function (GitHub $github, Request $request, Response $response, Database $dbForConsole, callable $getProjectDB) use ($createGitDeployments) {
$payload = $request->getRawPayload();
$signatureRemote = $request->getHeader('x-hub-signature-256', '');
$signatureLocal = App::getEnv('_APP_VCS_GITHUB_WEBHOOK_SECRET', '');
$signatureLocal = Http::getEnv('_APP_VCS_GITHUB_WEBHOOK_SECRET', '');
$valid = empty($signatureRemote) ? true : $github->validateWebhookEvent($payload, $signatureRemote, $signatureLocal);
@@ -805,8 +805,8 @@ App::post('/v1/vcs/github/events')
}
$event = $request->getHeader('x-github-event', '');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$parsedPayload = $github->getEvent($event, $payload);
if ($event == $github::EVENT_PUSH) {
@@ -921,7 +921,7 @@ App::post('/v1/vcs/github/events')
}
);
App::get('/v1/vcs/installations')
Http::get('/v1/vcs/installations')
->desc('List installations')
->groups(['api', 'vcs'])
->label('scope', 'vcs.read')
@@ -973,7 +973,7 @@ App::get('/v1/vcs/installations')
]), Response::MODEL_INSTALLATION_LIST);
});
App::get('/v1/vcs/installations/:installationId')
Http::get('/v1/vcs/installations/:installationId')
->desc('Get installation')
->groups(['api', 'vcs'])
->label('scope', 'vcs.read')
@@ -1002,7 +1002,7 @@ App::get('/v1/vcs/installations/:installationId')
$response->dynamic($installation, Response::MODEL_INSTALLATION);
});
App::delete('/v1/vcs/installations/:installationId')
Http::delete('/v1/vcs/installations/:installationId')
->desc('Delete Installation')
->groups(['api', 'vcs'])
->label('scope', 'vcs.write')
@@ -1035,7 +1035,7 @@ App::delete('/v1/vcs/installations/:installationId')
$response->noContent();
});
App::patch('/v1/vcs/github/installations/:installationId/repositories/:repositoryId')
Http::patch('/v1/vcs/github/installations/:installationId/repositories/:repositoryId')
->desc('Authorize external deployment')
->groups(['api', 'vcs'])
->label('scope', 'vcs.write')
@@ -1080,8 +1080,8 @@ App::patch('/v1/vcs/github/installations/:installationId/repositories/:repositor
$repository = $dbForConsole->updateDocument('repositories', $repository->getId(), $repository);
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
+338 -338
View File
@@ -2,7 +2,7 @@
require_once __DIR__ . '/../init.php';
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Helpers\Role;
use Utopia\Locale\Locale;
use Utopia\Logger\Logger;
@@ -32,20 +32,20 @@ use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\Hostname;
use Utopia\Http\Validator\Hostname;
use Appwrite\Utopia\Request\Filters\V12 as RequestV12;
use Appwrite\Utopia\Request\Filters\V13 as RequestV13;
use Appwrite\Utopia\Request\Filters\V14 as RequestV14;
use Appwrite\Utopia\Request\Filters\V15 as RequestV15;
use Appwrite\Utopia\Request\Filters\V16 as RequestV16;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\Text;
use Utopia\Http\Validator\WhiteList;
Config::setParam('domainVerification', false);
Config::setParam('cookieDomain', 'localhost');
Config::setParam('cookieSamesite', Response::COOKIE_SAMESITE_NONE);
function router(App $utopia, Database $dbForConsole, SwooleRequest $swooleRequest, Request $request, Response $response)
function router(Http $utopia, Database $dbForConsole, SwooleRequest $swooleRequest, Request $request, Response $response)
{
$utopia->getRoute()?->label('error', __DIR__ . '/../views/general/error.phtml');
@@ -59,15 +59,15 @@ function router(App $utopia, Database $dbForConsole, SwooleRequest $swooleReques
)[0] ?? null;
if ($route === null) {
if ($host === App::getEnv('_APP_DOMAIN_FUNCTIONS', '')) {
if ($host === Http::getEnv('_APP_DOMAIN_FUNCTIONS', '')) {
throw new AppwriteException(AppwriteException::GENERAL_ACCESS_FORBIDDEN, 'This domain cannot be used for security reasons. Please use any subdomain instead.');
}
if (\str_ends_with($host, App::getEnv('_APP_DOMAIN_FUNCTIONS', ''))) {
if (\str_ends_with($host, Http::getEnv('_APP_DOMAIN_FUNCTIONS', ''))) {
throw new AppwriteException(AppwriteException::GENERAL_ACCESS_FORBIDDEN, 'This domain is not connected to any Appwrite resource yet. Please configure custom domain or function domain to allow this request.');
}
if (App::getEnv('_APP_OPTIONS_ROUTER_PROTECTION', 'disabled') === 'enabled') {
if (Http::getEnv('_APP_OPTIONS_ROUTER_PROTECTION', 'disabled') === 'enabled') {
if ($host !== 'localhost' && $host !== APP_HOSTNAME_INTERNAL) { // localhost allowed for proxy, APP_HOSTNAME_INTERNAL allowed for migrations
throw new AppwriteException(AppwriteException::GENERAL_ACCESS_FORBIDDEN, 'Router protection does not allow accessing Appwrite over this domain. Please add it as custom domain to your project or disable _APP_OPTIONS_ROUTER_PROTECTION environment variable.');
}
@@ -98,7 +98,7 @@ function router(App $utopia, Database $dbForConsole, SwooleRequest $swooleReques
$type = $route->getAttribute('resourceType');
if ($type === 'function') {
if (App::getEnv('_APP_OPTIONS_FUNCTIONS_FORCE_HTTPS', 'disabled') === 'enabled') { // Force HTTPS
if (Http::getEnv('_APP_OPTIONS_FUNCTIONS_FORCE_HTTPS', 'disabled') === 'enabled') { // Force HTTPS
if ($request->getProtocol() !== 'https') {
if ($request->getMethod() !== Request::METHOD_GET) {
throw new AppwriteException(AppwriteException::GENERAL_PROTOCOL_UNSUPPORTED, 'Method unsupported over HTTP. Please use HTTPS instead.');
@@ -193,386 +193,386 @@ function router(App $utopia, Database $dbForConsole, SwooleRequest $swooleReques
return false;
}
App::init()
->groups(['api', 'web'])
->inject('utopia')
->inject('swooleRequest')
->inject('request')
->inject('response')
->inject('console')
->inject('project')
->inject('dbForConsole')
->inject('user')
->inject('locale')
->inject('localeCodes')
->inject('clients')
->inject('servers')
->action(function (App $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Document $console, Document $project, Database $dbForConsole, Document $user, Locale $locale, array $localeCodes, array $clients, array $servers) {
/*
* Appwrite Router
*/
// Http::init()
// ->groups(['api', 'web'])
// ->inject('utopia')
// ->inject('swooleRequest')
// ->inject('request')
// ->inject('response')
// ->inject('console')
// ->inject('project')
// ->inject('dbForConsole')
// ->inject('user')
// ->inject('locale')
// ->inject('localeCodes')
// ->inject('clients')
// ->inject('servers')
// ->action(function (Http $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Document $console, Document $project, Database $dbForConsole, Document $user, Locale $locale, array $localeCodes, array $clients, array $servers) {
// /*
// * Appwrite Router
// */
$host = $request->getHostname() ?? '';
$mainDomain = App::getEnv('_APP_DOMAIN', '');
// Only run Router when external domain
if ($host !== $mainDomain) {
if (router($utopia, $dbForConsole, $swooleRequest, $request, $response)) {
return;
}
}
// $host = $request->getHostname() ?? '';
// $mainDomain = Http::getEnv('_APP_DOMAIN', '');
// // Only run Router when external domain
// if ($host !== $mainDomain) {
// if (router($utopia, $dbForConsole, $swooleRequest, $request, $response)) {
// return;
// }
// }
/*
* Request format
*/
$route = $utopia->getRoute();
Request::setRoute($route);
// /*
// * Request format
// */
// $route = $utopia->getRoute();
// Request::setRoute($route);
if ($route === null) {
return $response->setStatusCode(404)->send('Not Found');
}
// if ($route === null) {
// return $response->setStatusCode(404)->send('Not Found');
// }
$requestFormat = $request->getHeader('x-appwrite-response-format', App::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
if ($requestFormat) {
switch ($requestFormat) {
case version_compare($requestFormat, '0.12.0', '<'):
Request::setFilter(new RequestV12());
break;
case version_compare($requestFormat, '0.13.0', '<'):
Request::setFilter(new RequestV13());
break;
case version_compare($requestFormat, '0.14.0', '<'):
Request::setFilter(new RequestV14());
break;
case version_compare($requestFormat, '0.15.3', '<'):
Request::setFilter(new RequestV15());
break;
case version_compare($requestFormat, '1.4.0', '<'):
Request::setFilter(new RequestV16());
break;
default:
Request::setFilter(null);
}
} else {
Request::setFilter(null);
}
// $requestFormat = $request->getHeader('x-appwrite-response-format', Http::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
// if ($requestFormat) {
// switch ($requestFormat) {
// case version_compare($requestFormat, '0.12.0', '<'):
// Request::setFilter(new RequestV12());
// break;
// case version_compare($requestFormat, '0.13.0', '<'):
// Request::setFilter(new RequestV13());
// break;
// case version_compare($requestFormat, '0.14.0', '<'):
// Request::setFilter(new RequestV14());
// break;
// case version_compare($requestFormat, '0.15.3', '<'):
// Request::setFilter(new RequestV15());
// break;
// case version_compare($requestFormat, '1.4.0', '<'):
// Request::setFilter(new RequestV16());
// break;
// default:
// Request::setFilter(null);
// }
// } else {
// Request::setFilter(null);
// }
$domain = $request->getHostname();
$domains = Config::getParam('domains', []);
if (!array_key_exists($domain, $domains)) {
$domain = new Domain(!empty($domain) ? $domain : '');
// $domain = $request->getHostname();
// $domains = Config::getParam('domains', []);
// if (!array_key_exists($domain, $domains)) {
// $domain = new Domain(!empty($domain) ? $domain : '');
if (empty($domain->get()) || !$domain->isKnown() || $domain->isTest()) {
$domains[$domain->get()] = false;
Console::warning($domain->get() . ' is not a publicly accessible domain. Skipping SSL certificate generation.');
} elseif (str_starts_with($request->getURI(), '/.well-known/acme-challenge')) {
Console::warning('Skipping SSL certificates generation on ACME challenge.');
} else {
Authorization::disable();
// if (empty($domain->get()) || !$domain->isKnown() || $domain->isTest()) {
// $domains[$domain->get()] = false;
// Console::warning($domain->get() . ' is not a publicly accessible domain. Skipping SSL certificate generation.');
// } elseif (str_starts_with($request->getURI(), '/.well-known/acme-challenge')) {
// Console::warning('Skipping SSL certificates generation on ACME challenge.');
// } else {
// Authorization::disable();
$envDomain = App::getEnv('_APP_DOMAIN', '');
$mainDomain = null;
if (!empty($envDomain) && $envDomain !== 'localhost') {
$mainDomain = $envDomain;
} else {
$domainDocument = $dbForConsole->findOne('rules', [Query::orderAsc('$id')]);
$mainDomain = $domainDocument ? $domainDocument->getAttribute('domain') : $domain->get();
}
// $envDomain = Http::getEnv('_APP_DOMAIN', '');
// $mainDomain = null;
// if (!empty($envDomain) && $envDomain !== 'localhost') {
// $mainDomain = $envDomain;
// } else {
// $domainDocument = $dbForConsole->findOne('rules', [Query::orderAsc('$id')]);
// $mainDomain = $domainDocument ? $domainDocument->getAttribute('domain') : $domain->get();
// }
if ($mainDomain !== $domain->get()) {
Console::warning($domain->get() . ' is not a main domain. Skipping SSL certificate generation.');
} else {
$domainDocument = $dbForConsole->findOne('rules', [
Query::equal('domain', [$domain->get()])
]);
// if ($mainDomain !== $domain->get()) {
// Console::warning($domain->get() . ' is not a main domain. Skipping SSL certificate generation.');
// } else {
// $domainDocument = $dbForConsole->findOne('rules', [
// Query::equal('domain', [$domain->get()])
// ]);
if (!$domainDocument) {
$domainDocument = new Document([
'domain' => $domain->get(),
'resourceType' => 'api',
'status' => 'verifying',
'projectId' => 'console',
'projectInternalId' => 'console'
]);
// if (!$domainDocument) {
// $domainDocument = new Document([
// 'domain' => $domain->get(),
// 'resourceType' => 'api',
// 'status' => 'verifying',
// 'projectId' => 'console',
// 'projectInternalId' => 'console'
// ]);
$domainDocument = $dbForConsole->createDocument('rules', $domainDocument);
// $domainDocument = $dbForConsole->createDocument('rules', $domainDocument);
Console::info('Issuing a TLS certificate for the main domain (' . $domain->get() . ') in a few seconds...');
// Console::info('Issuing a TLS certificate for the main domain (' . $domain->get() . ') in a few seconds...');
(new Certificate())
->setDomain($domainDocument)
->setSkipRenewCheck(true)
->trigger();
}
}
$domains[$domain->get()] = true;
// (new Certificate())
// ->setDomain($domainDocument)
// ->setSkipRenewCheck(true)
// ->trigger();
// }
// }
// $domains[$domain->get()] = true;
Authorization::reset(); // ensure authorization is re-enabled
}
Config::setParam('domains', $domains);
}
// Authorization::reset(); // ensure authorization is re-enabled
// }
// Config::setParam('domains', $domains);
// }
$localeParam = (string) $request->getParam('locale', $request->getHeader('x-appwrite-locale', ''));
if (\in_array($localeParam, $localeCodes)) {
$locale->setDefault($localeParam);
}
// $localeParam = (string) $request->getParam('locale', $request->getHeader('x-appwrite-locale', ''));
// if (\in_array($localeParam, $localeCodes)) {
// $locale->setDefault($localeParam);
// }
if ($project->isEmpty()) {
throw new AppwriteException(AppwriteException::PROJECT_NOT_FOUND);
}
// if ($project->isEmpty()) {
// throw new AppwriteException(AppwriteException::PROJECT_NOT_FOUND);
// }
if (!empty($route->getLabel('sdk.auth', [])) && $project->isEmpty() && ($route->getLabel('scope', '') !== 'public')) {
throw new AppwriteException(AppwriteException::PROJECT_UNKNOWN);
}
// if (!empty($route->getLabel('sdk.auth', [])) && $project->isEmpty() && ($route->getLabel('scope', '') !== 'public')) {
// throw new AppwriteException(AppwriteException::PROJECT_UNKNOWN);
// }
$referrer = $request->getReferer();
$origin = \parse_url($request->getOrigin($referrer), PHP_URL_HOST);
$protocol = \parse_url($request->getOrigin($referrer), PHP_URL_SCHEME);
$port = \parse_url($request->getOrigin($referrer), PHP_URL_PORT);
// $referrer = $request->getReferer();
// $origin = \parse_url($request->getOrigin($referrer), PHP_URL_HOST);
// $protocol = \parse_url($request->getOrigin($referrer), PHP_URL_SCHEME);
// $port = \parse_url($request->getOrigin($referrer), PHP_URL_PORT);
$refDomainOrigin = 'localhost';
$validator = new Hostname($clients);
if ($validator->isValid($origin)) {
$refDomainOrigin = $origin;
}
// $refDomainOrigin = 'localhost';
// $validator = new Hostname($clients);
// if ($validator->isValid($origin)) {
// $refDomainOrigin = $origin;
// }
$refDomain = (!empty($protocol) ? $protocol : $request->getProtocol()) . '://' . $refDomainOrigin . (!empty($port) ? ':' . $port : '');
// $refDomain = (!empty($protocol) ? $protocol : $request->getProtocol()) . '://' . $refDomainOrigin . (!empty($port) ? ':' . $port : '');
$refDomain = (!$route->getLabel('origin', false)) // This route is publicly accessible
? $refDomain
: (!empty($protocol) ? $protocol : $request->getProtocol()) . '://' . $origin . (!empty($port) ? ':' . $port : '');
// $refDomain = (!$route->getLabel('origin', false)) // This route is publicly accessible
// ? $refDomain
// : (!empty($protocol) ? $protocol : $request->getProtocol()) . '://' . $origin . (!empty($port) ? ':' . $port : '');
$selfDomain = new Domain($request->getHostname());
$endDomain = new Domain((string)$origin);
// $selfDomain = new Domain($request->getHostname());
// $endDomain = new Domain((string)$origin);
Config::setParam(
'domainVerification',
($selfDomain->getRegisterable() === $endDomain->getRegisterable()) &&
$endDomain->getRegisterable() !== ''
);
// Config::setParam(
// 'domainVerification',
// ($selfDomain->getRegisterable() === $endDomain->getRegisterable()) &&
// $endDomain->getRegisterable() !== ''
// );
$isLocalHost = $request->getHostname() === 'localhost' || $request->getHostname() === 'localhost:' . $request->getPort();
$isIpAddress = filter_var($request->getHostname(), FILTER_VALIDATE_IP) !== false;
// $isLocalHost = $request->getHostname() === 'localhost' || $request->getHostname() === 'localhost:' . $request->getPort();
// $isIpAddress = filter_var($request->getHostname(), FILTER_VALIDATE_IP) !== false;
$isConsoleProject = $project->getAttribute('$id', '') === 'console';
$isConsoleRootSession = App::getEnv('_APP_CONSOLE_ROOT_SESSION', 'disabled') === 'enabled';
// $isConsoleProject = $project->getAttribute('$id', '') === 'console';
// $isConsoleRootSession = Http::getEnv('_APP_CONSOLE_ROOT_SESSION', 'disabled') === 'enabled';
Config::setParam(
'cookieDomain',
$isLocalHost || $isIpAddress
? null
: ($isConsoleProject && $isConsoleRootSession
? '.' . $selfDomain->getRegisterable()
: '.' . $request->getHostname()
)
);
// Config::setParam(
// 'cookieDomain',
// $isLocalHost || $isIpAddress
// ? null
// : ($isConsoleProject && $isConsoleRootSession
// ? '.' . $selfDomain->getRegisterable()
// : '.' . $request->getHostname()
// )
// );
/*
* Response format
*/
$responseFormat = $request->getHeader('x-appwrite-response-format', App::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
if ($responseFormat) {
switch ($responseFormat) {
case version_compare($responseFormat, '0.11.2', '<='):
Response::setFilter(new ResponseV11());
break;
case version_compare($responseFormat, '0.12.4', '<='):
Response::setFilter(new ResponseV12());
break;
case version_compare($responseFormat, '0.13.4', '<='):
Response::setFilter(new ResponseV13());
break;
case version_compare($responseFormat, '0.14.0', '<='):
Response::setFilter(new ResponseV14());
break;
case version_compare($responseFormat, '0.15.3', '<='):
Response::setFilter(new ResponseV15());
break;
case version_compare($responseFormat, '1.4.0', '<'):
Response::setFilter(new ResponseV16());
break;
default:
Response::setFilter(null);
}
} else {
Response::setFilter(null);
}
// /*
// * Response format
// */
// $responseFormat = $request->getHeader('x-appwrite-response-format', Http::getEnv('_APP_SYSTEM_RESPONSE_FORMAT', ''));
// if ($responseFormat) {
// switch ($responseFormat) {
// case version_compare($responseFormat, '0.11.2', '<='):
// Response::setFilter(new ResponseV11());
// break;
// case version_compare($responseFormat, '0.12.4', '<='):
// Response::setFilter(new ResponseV12());
// break;
// case version_compare($responseFormat, '0.13.4', '<='):
// Response::setFilter(new ResponseV13());
// break;
// case version_compare($responseFormat, '0.14.0', '<='):
// Response::setFilter(new ResponseV14());
// break;
// case version_compare($responseFormat, '0.15.3', '<='):
// Response::setFilter(new ResponseV15());
// break;
// case version_compare($responseFormat, '1.4.0', '<'):
// Response::setFilter(new ResponseV16());
// break;
// default:
// Response::setFilter(null);
// }
// } else {
// Response::setFilter(null);
// }
/*
* Security Headers
*
* As recommended at:
* @see https://www.owasp.org/index.php/List_of_useful_HTTP_headers
*/
if (App::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'enabled') { // Force HTTPS
if ($request->getProtocol() !== 'https' && ($swooleRequest->header['host'] ?? '') !== 'localhost' && ($swooleRequest->header['host'] ?? '') !== APP_HOSTNAME_INTERNAL) { // localhost allowed for proxy, APP_HOSTNAME_INTERNAL allowed for migrations
if ($request->getMethod() !== Request::METHOD_GET) {
throw new AppwriteException(AppwriteException::GENERAL_PROTOCOL_UNSUPPORTED, 'Method unsupported over HTTP. Please use HTTPS instead.');
}
// /*
// * Security Headers
// *
// * As recommended at:
// * @see https://www.owasp.org/index.php/List_of_useful_HTTP_headers
// */
// if (Http::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled') === 'enabled') { // Force HTTPS
// if ($request->getProtocol() !== 'https' && ($swooleRequest->header['host'] ?? '') !== 'localhost' && ($swooleRequest->header['host'] ?? '') !== APP_HOSTNAME_INTERNAL) { // localhost allowed for proxy, APP_HOSTNAME_INTERNAL allowed for migrations
// if ($request->getMethod() !== Request::METHOD_GET) {
// throw new AppwriteException(AppwriteException::GENERAL_PROTOCOL_UNSUPPORTED, 'Method unsupported over HTTP. Please use HTTPS instead.');
// }
return $response->redirect('https://' . $request->getHostname() . $request->getURI());
}
}
// return $response->redirect('https://' . $request->getHostname() . $request->getURI());
// }
// }
if ($request->getProtocol() === 'https') {
$response->addHeader('Strict-Transport-Security', 'max-age=' . (60 * 60 * 24 * 126)); // 126 days
}
// if ($request->getProtocol() === 'https') {
// $response->addHeader('Strict-Transport-Security', 'max-age=' . (60 * 60 * 24 * 126)); // 126 days
// }
$response
->addHeader('Server', 'Appwrite')
->addHeader('X-Content-Type-Options', 'nosniff')
->addHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE')
->addHeader('Access-Control-Allow-Headers', 'Origin, Cookie, Set-Cookie, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Request-Headers, Accept, X-Appwrite-Project, X-Appwrite-Key, X-Appwrite-Locale, X-Appwrite-Mode, X-Appwrite-JWT, X-Appwrite-Response-Format, X-SDK-Version, X-SDK-Name, X-SDK-Language, X-SDK-Platform, X-SDK-GraphQL, X-Appwrite-ID, X-Appwrite-Timestamp, Content-Range, Range, Cache-Control, Expires, Pragma')
->addHeader('Access-Control-Expose-Headers', 'X-Fallback-Cookies')
->addHeader('Access-Control-Allow-Origin', $refDomain)
->addHeader('Access-Control-Allow-Credentials', 'true');
// $response
// ->addHeader('Server', 'Appwrite')
// ->addHeader('X-Content-Type-Options', 'nosniff')
// ->addHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE')
// ->addHeader('Access-Control-Allow-Headers', 'Origin, Cookie, Set-Cookie, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Request-Headers, Accept, X-Appwrite-Project, X-Appwrite-Key, X-Appwrite-Locale, X-Appwrite-Mode, X-Appwrite-JWT, X-Appwrite-Response-Format, X-SDK-Version, X-SDK-Name, X-SDK-Language, X-SDK-Platform, X-SDK-GraphQL, X-Appwrite-ID, X-Appwrite-Timestamp, Content-Range, Range, Cache-Control, Expires, Pragma')
// ->addHeader('Access-Control-Expose-Headers', 'X-Fallback-Cookies')
// ->addHeader('Access-Control-Allow-Origin', $refDomain)
// ->addHeader('Access-Control-Allow-Credentials', 'true');
/*
* Validate Client Domain - Check to avoid CSRF attack
* Adding Appwrite API domains to allow XDOMAIN communication
* Skip this check for non-web platforms which are not required to send an origin header
*/
$origin = $request->getOrigin($request->getReferer(''));
$originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', [])));
// /*
// * Validate Client Domain - Check to avoid CSRF attack
// * Adding Appwrite API domains to allow XDOMAIN communication
// * Skip this check for non-web platforms which are not required to send an origin header
// */
// $origin = $request->getOrigin($request->getReferer(''));
// $originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', [])));
if (
!$originValidator->isValid($origin)
&& \in_array($request->getMethod(), [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE])
&& $route->getLabel('origin', false) !== '*'
&& empty($request->getHeader('x-appwrite-key', ''))
) {
throw new AppwriteException(AppwriteException::GENERAL_UNKNOWN_ORIGIN, $originValidator->getDescription());
}
// if (
// !$originValidator->isValid($origin)
// && \in_array($request->getMethod(), [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE])
// && $route->getLabel('origin', false) !== '*'
// && empty($request->getHeader('x-appwrite-key', ''))
// ) {
// throw new AppwriteException(AppwriteException::GENERAL_UNKNOWN_ORIGIN, $originValidator->getDescription());
// }
/*
* ACL Check
*/
$role = ($user->isEmpty())
? Role::guests()->toString()
: Role::users()->toString();
// /*
// * ACL Check
// */
// $role = ($user->isEmpty())
// ? Role::guests()->toString()
// : Role::users()->toString();
// Add user roles
$memberships = $user->find('teamId', $project->getAttribute('teamId'), 'memberships');
// // Add user roles
// $memberships = $user->find('teamId', $project->getAttribute('teamId'), 'memberships');
if ($memberships) {
foreach ($memberships->getAttribute('roles', []) as $memberRole) {
switch ($memberRole) {
case 'owner':
$role = Auth::USER_ROLE_OWNER;
break;
case 'admin':
$role = Auth::USER_ROLE_ADMIN;
break;
case 'developer':
$role = Auth::USER_ROLE_DEVELOPER;
break;
}
}
}
// if ($memberships) {
// foreach ($memberships->getAttribute('roles', []) as $memberRole) {
// switch ($memberRole) {
// case 'owner':
// $role = Auth::USER_ROLE_OWNER;
// break;
// case 'admin':
// $role = Auth::USER_ROLE_ADMIN;
// break;
// case 'developer':
// $role = Auth::USER_ROLE_DEVELOPER;
// break;
// }
// }
// }
$roles = Config::getParam('roles', []);
$scope = $route->getLabel('scope', 'none'); // Allowed scope for chosen route
$scopes = $roles[$role]['scopes']; // Allowed scopes for user role
// $roles = Config::getParam('roles', []);
// $scope = $route->getLabel('scope', 'none'); // Allowed scope for chosen route
// $scopes = $roles[$role]['scopes']; // Allowed scopes for user role
$authKey = $request->getHeader('x-appwrite-key', '');
// $authKey = $request->getHeader('x-appwrite-key', '');
if (!empty($authKey)) { // API Key authentication
// Check if given key match project API keys
$key = $project->find('secret', $authKey, 'keys');
// if (!empty($authKey)) { // API Key authentication
// // Check if given key match project API keys
// $key = $project->find('secret', $authKey, 'keys');
/*
* Try app auth when we have project key and no user
* Mock user to app and grant API key scopes in addition to default app scopes
*/
if ($key && $user->isEmpty()) {
$user = new Document([
'$id' => '',
'status' => true,
'email' => 'app.' . $project->getId() . '@service.' . $request->getHostname(),
'password' => '',
'name' => $project->getAttribute('name', 'Untitled'),
]);
// /*
// * Try app auth when we have project key and no user
// * Mock user to app and grant API key scopes in addition to default app scopes
// */
// if ($key && $user->isEmpty()) {
// $user = new Document([
// '$id' => '',
// 'status' => true,
// 'email' => 'app.' . $project->getId() . '@service.' . $request->getHostname(),
// 'password' => '',
// 'name' => $project->getAttribute('name', 'Untitled'),
// ]);
$role = Auth::USER_ROLE_APPS;
$scopes = \array_merge($roles[$role]['scopes'], $key->getAttribute('scopes', []));
// $role = Auth::USER_ROLE_APPS;
// $scopes = \array_merge($roles[$role]['scopes'], $key->getAttribute('scopes', []));
$expire = $key->getAttribute('expire');
if (!empty($expire) && $expire < DateTime::formatTz(DateTime::now())) {
throw new AppwriteException(AppwriteException::PROJECT_KEY_EXPIRED);
}
// $expire = $key->getAttribute('expire');
// if (!empty($expire) && $expire < DateTime::formatTz(DateTime::now())) {
// throw new AppwriteException(AppwriteException::PROJECT_KEY_EXPIRED);
// }
Authorization::setRole(Auth::USER_ROLE_APPS);
Authorization::setDefaultStatus(false); // Cancel security segmentation for API keys.
// Authorization::setRole(Auth::USER_ROLE_APPS);
// Authorization::setDefaultStatus(false); // Cancel security segmentation for API keys.
$accessedAt = $key->getAttribute('accessedAt', '');
if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_KEY_ACCCESS)) > $accessedAt) {
$key->setAttribute('accessedAt', DateTime::now());
$dbForConsole->updateDocument('keys', $key->getId(), $key);
$dbForConsole->deleteCachedDocument('projects', $project->getId());
}
// $accessedAt = $key->getAttribute('accessedAt', '');
// if (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_KEY_ACCCESS)) > $accessedAt) {
// $key->setAttribute('accessedAt', DateTime::now());
// $dbForConsole->updateDocument('keys', $key->getId(), $key);
// $dbForConsole->deleteCachedDocument('projects', $project->getId());
// }
$sdkValidator = new WhiteList($servers, true);
$sdk = $request->getHeader('x-sdk-name', 'UNKNOWN');
if ($sdkValidator->isValid($sdk)) {
$sdks = $key->getAttribute('sdks', []);
if (!in_array($sdk, $sdks)) {
array_push($sdks, $sdk);
$key->setAttribute('sdks', $sdks);
// $sdkValidator = new WhiteList($servers, true);
// $sdk = $request->getHeader('x-sdk-name', 'UNKNOWN');
// if ($sdkValidator->isValid($sdk)) {
// $sdks = $key->getAttribute('sdks', []);
// if (!in_array($sdk, $sdks)) {
// array_push($sdks, $sdk);
// $key->setAttribute('sdks', $sdks);
/** Update access time as well */
$key->setAttribute('accessedAt', Datetime::now());
$dbForConsole->updateDocument('keys', $key->getId(), $key);
$dbForConsole->deleteCachedDocument('projects', $project->getId());
}
}
}
}
// /** Update access time as well */
// $key->setAttribute('accessedAt', Datetime::now());
// $dbForConsole->updateDocument('keys', $key->getId(), $key);
// $dbForConsole->deleteCachedDocument('projects', $project->getId());
// }
// }
// }
// }
Authorization::setRole($role);
// Authorization::setRole($role);
foreach (Auth::getRoles($user) as $authRole) {
Authorization::setRole($authRole);
}
// foreach (Auth::getRoles($user) as $authRole) {
// Authorization::setRole($authRole);
// }
$service = $route->getLabel('sdk.namespace', '');
if (!empty($service)) {
if (
array_key_exists($service, $project->getAttribute('services', []))
&& !$project->getAttribute('services', [])[$service]
&& !(Auth::isPrivilegedUser(Authorization::getRoles()) || Auth::isAppUser(Authorization::getRoles()))
) {
throw new AppwriteException(AppwriteException::GENERAL_SERVICE_DISABLED);
}
}
// $service = $route->getLabel('sdk.namespace', '');
// if (!empty($service)) {
// if (
// array_key_exists($service, $project->getAttribute('services', []))
// && !$project->getAttribute('services', [])[$service]
// && !(Auth::isPrivilegedUser(Authorization::getRoles()) || Auth::isAppUser(Authorization::getRoles()))
// ) {
// throw new AppwriteException(AppwriteException::GENERAL_SERVICE_DISABLED);
// }
// }
if (!\in_array($scope, $scopes)) {
if ($project->isEmpty()) { // Check if permission is denied because project is missing
throw new AppwriteException(AppwriteException::PROJECT_NOT_FOUND);
}
// if (!\in_array($scope, $scopes)) {
// if ($project->isEmpty()) { // Check if permission is denied because project is missing
// throw new AppwriteException(AppwriteException::PROJECT_NOT_FOUND);
// }
throw new AppwriteException(AppwriteException::GENERAL_UNAUTHORIZED_SCOPE, $user->getAttribute('email', 'User') . ' (role: ' . \strtolower($roles[$role]['label']) . ') missing scope (' . $scope . ')');
}
// throw new AppwriteException(AppwriteException::GENERAL_UNAUTHORIZED_SCOPE, $user->getAttribute('email', 'User') . ' (role: ' . \strtolower($roles[$role]['label']) . ') missing scope (' . $scope . ')');
// }
if (false === $user->getAttribute('status')) { // Account is blocked
throw new AppwriteException(AppwriteException::USER_BLOCKED);
}
// if (false === $user->getAttribute('status')) { // Account is blocked
// throw new AppwriteException(AppwriteException::USER_BLOCKED);
// }
if ($user->getAttribute('reset')) {
throw new AppwriteException(AppwriteException::USER_PASSWORD_RESET_REQUIRED);
}
});
// if ($user->getAttribute('reset')) {
// throw new AppwriteException(AppwriteException::USER_PASSWORD_RESET_REQUIRED);
// }
// });
App::options()
Http::options()
->inject('utopia')
->inject('swooleRequest')
->inject('request')
->inject('response')
->inject('dbForConsole')
->action(function (App $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Database $dbForConsole) {
->action(function (Http $utopia, SwooleRequest $swooleRequest, Request $request, Response $response, Database $dbForConsole) {
/*
* Appwrite Router
*/
$host = $request->getHostname() ?? '';
$mainDomain = App::getEnv('_APP_DOMAIN', '');
$mainDomain = Http::getEnv('_APP_DOMAIN', '');
// Only run Router when external domain
if ($host !== $mainDomain) {
if (router($utopia, $dbForConsole, $swooleRequest, $request, $response)) {
@@ -592,7 +592,7 @@ App::options()
->noContent();
});
App::error()
Http::error()
->inject('error')
->inject('utopia')
->inject('request')
@@ -600,9 +600,9 @@ App::error()
->inject('project')
->inject('logger')
->inject('loggerBreadcrumbs')
->action(function (Throwable $error, App $utopia, Request $request, Response $response, Document $project, ?Logger $logger, array $loggerBreadcrumbs) {
->action(function (Throwable $error, Http $utopia, Request $request, Response $response, Document $project, ?Logger $logger, array $loggerBreadcrumbs) {
$version = App::getEnv('_APP_VERSION', 'UNKNOWN');
$version = Http::getEnv('_APP_VERSION', 'UNKNOWN');
$route = $utopia->getRoute();
if ($logger) {
@@ -644,7 +644,7 @@ App::error()
$action = $route->getLabel("sdk.namespace", "UNKNOWN_NAMESPACE") . '.' . $route->getLabel("sdk.method", "UNKNOWN_METHOD");
$log->setAction($action);
$isProduction = App::getEnv('_APP_ENV', 'development') === 'production';
$isProduction = Http::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
foreach ($loggerBreadcrumbs as $loggerBreadcrumb) {
@@ -677,7 +677,7 @@ App::error()
}
/** Handle Utopia Errors */
if ($error instanceof Utopia\Exception) {
if ($error instanceof Utopia\Http\Exception) {
$error = new AppwriteException(AppwriteException::GENERAL_UNKNOWN, $message, $code, $error);
switch ($code) {
case 400:
@@ -720,7 +720,7 @@ App::error()
$type = $error->getType();
$output = ((App::isDevelopment())) ? [
$output = ((Http::isDevelopment())) ? [
'message' => $message,
'code' => $code,
'file' => $file,
@@ -748,7 +748,7 @@ App::error()
$layout
->setParam('title', $project->getAttribute('name') . ' - Error')
->setParam('development', App::isDevelopment())
->setParam('development', Http::isDevelopment())
->setParam('projectName', $project->getAttribute('name'))
->setParam('projectURL', $project->getAttribute('url'))
->setParam('message', $error->getMessage())
@@ -765,7 +765,7 @@ App::error()
);
});
App::get('/robots.txt')
Http::get('/robots.txt')
->desc('Robots.txt File')
->label('scope', 'public')
->label('docs', false)
@@ -775,7 +775,7 @@ App::get('/robots.txt')
$response->text($template->render(false));
});
App::get('/humans.txt')
Http::get('/humans.txt')
->desc('Humans.txt File')
->label('scope', 'public')
->label('docs', false)
@@ -785,7 +785,7 @@ App::get('/humans.txt')
$response->text($template->render(false));
});
App::get('/.well-known/acme-challenge/*')
Http::get('/.well-known/acme-challenge/*')
->desc('SSL Verification')
->label('scope', 'public')
->label('docs', false)
@@ -838,7 +838,7 @@ App::get('/.well-known/acme-challenge/*')
include_once __DIR__ . '/shared/api.php';
include_once __DIR__ . '/shared/api/auth.php';
App::wildcard()
Http::wildcard()
->groups(['api'])
->label('scope', 'global')
->action(function () {
+39 -39
View File
@@ -4,21 +4,21 @@ global $utopia, $request, $response;
use Appwrite\Extend\Exception;
use Utopia\Database\Document;
use Utopia\Validator\Host;
use Utopia\Http\Validator\Host;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Database;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Integer;
use Utopia\Validator\Text;
use Utopia\Http\Validator\ArrayList;
use Utopia\Http\Validator\Integer;
use Utopia\Http\Validator\Text;
use Utopia\Storage\Validator\File;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\WhiteList;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\UID;
use Utopia\Validator\Nullable;
use Utopia\Http\Validator\Nullable;
App::get('/v1/mock/tests/foo')
Http::get('/v1/mock/tests/foo')
->desc('Get Foo')
->groups(['mock'])
->label('scope', 'public')
@@ -36,7 +36,7 @@ App::get('/v1/mock/tests/foo')
->action(function ($x, $y, $z) {
});
App::post('/v1/mock/tests/foo')
Http::post('/v1/mock/tests/foo')
->desc('Post Foo')
->groups(['mock'])
->label('scope', 'public')
@@ -54,7 +54,7 @@ App::post('/v1/mock/tests/foo')
->action(function ($x, $y, $z) {
});
App::patch('/v1/mock/tests/foo')
Http::patch('/v1/mock/tests/foo')
->desc('Patch Foo')
->groups(['mock'])
->label('scope', 'public')
@@ -72,7 +72,7 @@ App::patch('/v1/mock/tests/foo')
->action(function ($x, $y, $z) {
});
App::put('/v1/mock/tests/foo')
Http::put('/v1/mock/tests/foo')
->desc('Put Foo')
->groups(['mock'])
->label('scope', 'public')
@@ -90,7 +90,7 @@ App::put('/v1/mock/tests/foo')
->action(function ($x, $y, $z) {
});
App::delete('/v1/mock/tests/foo')
Http::delete('/v1/mock/tests/foo')
->desc('Delete Foo')
->groups(['mock'])
->label('scope', 'public')
@@ -108,7 +108,7 @@ App::delete('/v1/mock/tests/foo')
->action(function ($x, $y, $z) {
});
App::get('/v1/mock/tests/bar')
Http::get('/v1/mock/tests/bar')
->desc('Get Bar')
->groups(['mock'])
->label('scope', 'public')
@@ -126,7 +126,7 @@ App::get('/v1/mock/tests/bar')
->action(function ($required, $default, $z) {
});
App::post('/v1/mock/tests/bar')
Http::post('/v1/mock/tests/bar')
->desc('Post Bar')
->groups(['mock'])
->label('scope', 'public')
@@ -146,7 +146,7 @@ App::post('/v1/mock/tests/bar')
->action(function ($required, $default, $z) {
});
App::patch('/v1/mock/tests/bar')
Http::patch('/v1/mock/tests/bar')
->desc('Patch Bar')
->groups(['mock'])
->label('scope', 'public')
@@ -164,7 +164,7 @@ App::patch('/v1/mock/tests/bar')
->action(function ($required, $default, $z) {
});
App::put('/v1/mock/tests/bar')
Http::put('/v1/mock/tests/bar')
->desc('Put Bar')
->groups(['mock'])
->label('scope', 'public')
@@ -182,7 +182,7 @@ App::put('/v1/mock/tests/bar')
->action(function ($required, $default, $z) {
});
App::delete('/v1/mock/tests/bar')
Http::delete('/v1/mock/tests/bar')
->desc('Delete Bar')
->groups(['mock'])
->label('scope', 'public')
@@ -200,7 +200,7 @@ App::delete('/v1/mock/tests/bar')
->action(function ($required, $default, $z) {
});
App::get('/v1/mock/tests/general/headers')
Http::get('/v1/mock/tests/general/headers')
->desc('Get headers')
->groups(['mock'])
->label('scope', 'public')
@@ -228,7 +228,7 @@ App::get('/v1/mock/tests/general/headers')
$response->dynamic(new Document(['result' => $res]), Response::MODEL_MOCK);
});
App::get('/v1/mock/tests/general/download')
Http::get('/v1/mock/tests/general/download')
->desc('Download File')
->groups(['mock'])
->label('scope', 'public')
@@ -252,7 +252,7 @@ App::get('/v1/mock/tests/general/download')
;
});
App::post('/v1/mock/tests/general/upload')
Http::post('/v1/mock/tests/general/upload')
->desc('Upload File')
->groups(['mock'])
->label('scope', 'public')
@@ -340,7 +340,7 @@ App::post('/v1/mock/tests/general/upload')
}
});
App::get('/v1/mock/tests/general/redirect')
Http::get('/v1/mock/tests/general/redirect')
->desc('Redirect')
->groups(['mock'])
->label('scope', 'public')
@@ -358,7 +358,7 @@ App::get('/v1/mock/tests/general/redirect')
$response->redirect('/v1/mock/tests/general/redirect/done');
});
App::get('/v1/mock/tests/general/redirect/done')
Http::get('/v1/mock/tests/general/redirect/done')
->desc('Redirected')
->groups(['mock'])
->label('scope', 'public')
@@ -373,7 +373,7 @@ App::get('/v1/mock/tests/general/redirect/done')
->action(function () {
});
App::get('/v1/mock/tests/general/set-cookie')
Http::get('/v1/mock/tests/general/set-cookie')
->desc('Set Cookie')
->groups(['mock'])
->label('scope', 'public')
@@ -392,7 +392,7 @@ App::get('/v1/mock/tests/general/set-cookie')
$response->addCookie('cookieName', 'cookieValue', \time() + 31536000, '/', $request->getHostname(), true, true);
});
App::get('/v1/mock/tests/general/get-cookie')
Http::get('/v1/mock/tests/general/get-cookie')
->desc('Get Cookie')
->groups(['mock'])
->label('scope', 'public')
@@ -412,7 +412,7 @@ App::get('/v1/mock/tests/general/get-cookie')
}
});
App::get('/v1/mock/tests/general/empty')
Http::get('/v1/mock/tests/general/empty')
->desc('Empty Response')
->groups(['mock'])
->label('scope', 'public')
@@ -429,7 +429,7 @@ App::get('/v1/mock/tests/general/empty')
$response->noContent();
});
App::post('/v1/mock/tests/general/nullable')
Http::post('/v1/mock/tests/general/nullable')
->desc('Nullable Test')
->groups(['mock'])
->label('scope', 'public')
@@ -444,7 +444,7 @@ App::post('/v1/mock/tests/general/nullable')
->action(function (string $required, string $nullable, ?string $optional) {
});
App::post('/v1/mock/tests/general/enum')
Http::post('/v1/mock/tests/general/enum')
->desc('Enum Test')
->groups(['mock'])
->label('scope', 'public')
@@ -457,7 +457,7 @@ App::post('/v1/mock/tests/general/enum')
->action(function (string $mockType) {
});
App::get('/v1/mock/tests/general/400-error')
Http::get('/v1/mock/tests/general/400-error')
->desc('400 Error')
->groups(['mock'])
->label('scope', 'public')
@@ -473,7 +473,7 @@ App::get('/v1/mock/tests/general/400-error')
throw new Exception(Exception::GENERAL_MOCK, 'Mock 400 error');
});
App::get('/v1/mock/tests/general/500-error')
Http::get('/v1/mock/tests/general/500-error')
->desc('500 Error')
->groups(['mock'])
->label('scope', 'public')
@@ -489,7 +489,7 @@ App::get('/v1/mock/tests/general/500-error')
throw new Exception(Exception::GENERAL_MOCK, 'Mock 500 error', 500);
});
App::get('/v1/mock/tests/general/502-error')
Http::get('/v1/mock/tests/general/502-error')
->desc('502 Error')
->groups(['mock'])
->label('scope', 'public')
@@ -510,7 +510,7 @@ App::get('/v1/mock/tests/general/502-error')
;
});
App::get('/v1/mock/tests/general/oauth2')
Http::get('/v1/mock/tests/general/oauth2')
->desc('OAuth Login')
->groups(['mock'])
->label('scope', 'public')
@@ -526,7 +526,7 @@ App::get('/v1/mock/tests/general/oauth2')
$response->redirect($redirectURI . '?' . \http_build_query(['code' => 'abcdef', 'state' => $state]));
});
App::get('/v1/mock/tests/general/oauth2/token')
Http::get('/v1/mock/tests/general/oauth2/token')
->desc('OAuth2 Token')
->groups(['mock'])
->label('scope', 'public')
@@ -572,7 +572,7 @@ App::get('/v1/mock/tests/general/oauth2/token')
}
});
App::get('/v1/mock/tests/general/oauth2/user')
Http::get('/v1/mock/tests/general/oauth2/user')
->desc('OAuth2 User')
->groups(['mock'])
->label('scope', 'public')
@@ -592,7 +592,7 @@ App::get('/v1/mock/tests/general/oauth2/user')
]);
});
App::get('/v1/mock/tests/general/oauth2/success')
Http::get('/v1/mock/tests/general/oauth2/success')
->desc('OAuth2 Success')
->groups(['mock'])
->label('scope', 'public')
@@ -605,7 +605,7 @@ App::get('/v1/mock/tests/general/oauth2/success')
]);
});
App::get('/v1/mock/tests/general/oauth2/failure')
Http::get('/v1/mock/tests/general/oauth2/failure')
->desc('OAuth2 Failure')
->groups(['mock'])
->label('scope', 'public')
@@ -620,7 +620,7 @@ App::get('/v1/mock/tests/general/oauth2/failure')
]);
});
App::patch('/v1/mock/functions-v2')
Http::patch('/v1/mock/functions-v2')
->desc('Update Function Version to V2 (outdated code syntax)')
->groups(['mock', 'api', 'functions'])
->label('scope', 'functions.write')
@@ -629,7 +629,7 @@ App::patch('/v1/mock/functions-v2')
->inject('response')
->inject('dbForProject')
->action(function (string $functionId, Response $response, Database $dbForProject) {
$isDevelopment = App::getEnv('_APP_ENV', 'development') === 'development';
$isDevelopment = Http::getEnv('_APP_ENV', 'development') === 'development';
if (!$isDevelopment) {
throw new Exception(Exception::GENERAL_NOT_IMPLEMENTED);
@@ -646,12 +646,12 @@ App::patch('/v1/mock/functions-v2')
$response->noContent();
});
App::shutdown()
Http::shutdown()
->groups(['mock'])
->inject('utopia')
->inject('response')
->inject('request')
->action(function (App $utopia, Response $response, Request $request) {
->action(function (Http $utopia, Response $response, Request $request) {
$result = [];
$route = $utopia->getRoute();
+191 -191
View File
@@ -12,7 +12,7 @@ use Appwrite\Messaging\Adapter\Realtime;
use Appwrite\Usage\Stats;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Request;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\Cache\Adapter\Filesystem;
@@ -89,230 +89,230 @@ $databaseListener = function (string $event, Document $document, Stats $usage) {
}
};
App::init()
->groups(['api'])
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('user')
->inject('events')
->inject('audits')
->inject('deletes')
->inject('database')
->inject('dbForProject')
->inject('mode')
->inject('mails')
->inject('usage')
->action(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Delete $deletes, EventDatabase $database, Database $dbForProject, string $mode, Mail $mails, Stats $usage) use ($databaseListener) {
// Http::init()
// ->groups(['api'])
// ->inject('utopia')
// ->inject('request')
// ->inject('response')
// ->inject('project')
// ->inject('user')
// ->inject('events')
// ->inject('audits')
// ->inject('deletes')
// ->inject('database')
// ->inject('dbForProject')
// ->inject('mode')
// ->inject('mails')
// ->inject('usage')
// ->action(function (Http $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Delete $deletes, EventDatabase $database, Database $dbForProject, string $mode, Mail $mails, Stats $usage) use ($databaseListener) {
$route = $utopia->getRoute();
// $route = $utopia->getRoute();
if ($project->isEmpty() && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope
throw new Exception(Exception::PROJECT_UNKNOWN);
}
// if ($project->isEmpty() && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope
// throw new Exception(Exception::PROJECT_UNKNOWN);
// }
/*
* Abuse Check
*/
$abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');
$timeLimitArray = [];
// /*
// * Abuse Check
// */
// $abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');
// $timeLimitArray = [];
$abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel;
// $abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel;
foreach ($abuseKeyLabel as $abuseKey) {
$timeLimit = new TimeLimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForProject);
$timeLimit
->setParam('{userId}', $user->getId())
->setParam('{userAgent}', $request->getUserAgent(''))
->setParam('{ip}', $request->getIP())
->setParam('{url}', $request->getHostname() . $route->getPath())
->setParam('{method}', $request->getMethod());
$timeLimitArray[] = $timeLimit;
}
// foreach ($abuseKeyLabel as $abuseKey) {
// $timeLimit = new TimeLimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForProject);
// $timeLimit
// ->setParam('{userId}', $user->getId())
// ->setParam('{userAgent}', $request->getUserAgent(''))
// ->setParam('{ip}', $request->getIP())
// ->setParam('{url}', $request->getHostname() . $route->getPath())
// ->setParam('{method}', $request->getMethod());
// $timeLimitArray[] = $timeLimit;
// }
$closestLimit = null;
// $closestLimit = null;
$roles = Authorization::getRoles();
$isPrivilegedUser = Auth::isPrivilegedUser($roles);
$isAppUser = Auth::isAppUser($roles);
// $roles = Authorization::getRoles();
// $isPrivilegedUser = Auth::isPrivilegedUser($roles);
// $isAppUser = Auth::isAppUser($roles);
foreach ($timeLimitArray as $timeLimit) {
foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys
if (!empty($value)) {
$timeLimit->setParam('{param-' . $key . '}', (\is_array($value)) ? \json_encode($value) : $value);
}
}
// foreach ($timeLimitArray as $timeLimit) {
// foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys
// if (!empty($value)) {
// $timeLimit->setParam('{param-' . $key . '}', (\is_array($value)) ? \json_encode($value) : $value);
// }
// }
$abuse = new Abuse($timeLimit);
$remaining = $timeLimit->remaining();
$limit = $timeLimit->limit();
$time = (new \DateTime($timeLimit->time()))->getTimestamp() + $route->getLabel('abuse-time', 3600);
// $abuse = new Abuse($timeLimit);
// $remaining = $timeLimit->remaining();
// $limit = $timeLimit->limit();
// $time = (new \DateTime($timeLimit->time()))->getTimestamp() + $route->getLabel('abuse-time', 3600);
if ($limit && ($remaining < $closestLimit || is_null($closestLimit))) {
$closestLimit = $remaining;
$response
->addHeader('X-RateLimit-Limit', $limit)
->addHeader('X-RateLimit-Remaining', $remaining)
->addHeader('X-RateLimit-Reset', $time)
;
}
// if ($limit && ($remaining < $closestLimit || is_null($closestLimit))) {
// $closestLimit = $remaining;
// $response
// ->addHeader('X-RateLimit-Limit', $limit)
// ->addHeader('X-RateLimit-Remaining', $remaining)
// ->addHeader('X-RateLimit-Reset', $time)
// ;
// }
$enabled = App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled';
// $enabled = Http::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled';
if (
$enabled // Abuse is enabled
&& !$isAppUser // User is not API key
&& !$isPrivilegedUser // User is not an admin
&& $abuse->check() // Route is rate-limited
) {
throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED);
}
}
// if (
// $enabled // Abuse is enabled
// && !$isAppUser // User is not API key
// && !$isPrivilegedUser // User is not an admin
// && $abuse->check() // Route is rate-limited
// ) {
// throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED);
// }
// }
/*
* Background Jobs
*/
$events
->setEvent($route->getLabel('event', ''))
->setProject($project)
->setUser($user);
// /*
// * Background Jobs
// */
// $events
// ->setEvent($route->getLabel('event', ''))
// ->setProject($project)
// ->setUser($user);
$audits
->setMode($mode)
->setUserAgent($request->getUserAgent(''))
->setIP($request->getIP())
->setEvent($route->getLabel('audits.event', ''))
->setProject($project)
->setUser($user);
// $audits
// ->setMode($mode)
// ->setUserAgent($request->getUserAgent(''))
// ->setIP($request->getIP())
// ->setEvent($route->getLabel('audits.event', ''))
// ->setProject($project)
// ->setUser($user);
$usage
->setParam('projectInternalId', $project->getInternalId())
->setParam('projectId', $project->getId())
->setParam('project.{scope}.network.requests', 1)
->setParam('httpMethod', $request->getMethod())
->setParam('project.{scope}.network.inbound', 0)
->setParam('project.{scope}.network.outbound', 0);
// $usage
// ->setParam('projectInternalId', $project->getInternalId())
// ->setParam('projectId', $project->getId())
// ->setParam('project.{scope}.network.requests', 1)
// ->setParam('httpMethod', $request->getMethod())
// ->setParam('project.{scope}.network.inbound', 0)
// ->setParam('project.{scope}.network.outbound', 0);
$deletes->setProject($project);
$database->setProject($project);
// $deletes->setProject($project);
// $database->setProject($project);
$dbForProject->on(Database::EVENT_DOCUMENT_CREATE, 'calculate-usage', fn ($event, Document $document) => $databaseListener($event, $document, $usage));
$dbForProject->on(Database::EVENT_DOCUMENT_DELETE, 'calculate-usage', fn ($event, Document $document) => $databaseListener($event, $document, $usage));
// $dbForProject->on(Database::EVENT_DOCUMENT_CREATE, 'calculate-usage', fn ($event, Document $document) => $databaseListener($event, $document, $usage));
// $dbForProject->on(Database::EVENT_DOCUMENT_DELETE, 'calculate-usage', fn ($event, Document $document) => $databaseListener($event, $document, $usage));
$useCache = $route->getLabel('cache', false);
// $useCache = $route->getLabel('cache', false);
if ($useCache) {
$key = md5($request->getURI() . implode('*', $request->getParams()) . '*' . APP_CACHE_BUSTER);
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
);
$timestamp = 60 * 60 * 24 * 30;
$data = $cache->load($key, $timestamp);
// if ($useCache) {
// $key = md5($request->getURI() . implode('*', $request->getParams()) . '*' . APP_CACHE_BUSTER);
// $cache = new Cache(
// new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
// );
// $timestamp = 60 * 60 * 24 * 30;
// $data = $cache->load($key, $timestamp);
if (!empty($data)) {
$data = json_decode($data, true);
$parts = explode('/', $data['resourceType']);
$type = $parts[0] ?? null;
// if (!empty($data)) {
// $data = json_decode($data, true);
// $parts = explode('/', $data['resourceType']);
// $type = $parts[0] ?? null;
if ($type === 'bucket') {
$bucketId = $parts[1] ?? null;
// if ($type === 'bucket') {
// $bucketId = $parts[1] ?? null;
$bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));
// $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));
$isAPIKey = Auth::isAppUser(Authorization::getRoles());
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
// $isAPIKey = Auth::isAppUser(Authorization::getRoles());
// $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {
throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);
}
// if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && !$isAPIKey && !$isPrivilegedUser)) {
// throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);
// }
$fileSecurity = $bucket->getAttribute('fileSecurity', false);
$validator = new Authorization(Database::PERMISSION_READ);
$valid = $validator->isValid($bucket->getRead());
if (!$fileSecurity && !$valid) {
throw new Exception(Exception::USER_UNAUTHORIZED);
}
// $fileSecurity = $bucket->getAttribute('fileSecurity', false);
// $validator = new Authorization(Database::PERMISSION_READ);
// $valid = $validator->isValid($bucket->getRead());
// if (!$fileSecurity && !$valid) {
// throw new Exception(Exception::USER_UNAUTHORIZED);
// }
$parts = explode('/', $data['resource']);
$fileId = $parts[1] ?? null;
// $parts = explode('/', $data['resource']);
// $fileId = $parts[1] ?? null;
if ($fileSecurity && !$valid) {
$file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);
} else {
$file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));
}
// if ($fileSecurity && !$valid) {
// $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);
// } else {
// $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));
// }
if ($file->isEmpty()) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
}
}
// if ($file->isEmpty()) {
// throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
// }
// }
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $timestamp) . ' GMT')
->addHeader('X-Appwrite-Cache', 'hit')
->setContentType($data['contentType'])
->send(base64_decode($data['payload']))
;
} else {
$response->addHeader('X-Appwrite-Cache', 'miss');
}
}
});
// $response
// ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $timestamp) . ' GMT')
// ->addHeader('X-Appwrite-Cache', 'hit')
// ->setContentType($data['contentType'])
// ->send(base64_decode($data['payload']))
// ;
// } else {
// $response->addHeader('X-Appwrite-Cache', 'miss');
// }
// }
// });
App::init()
->groups(['auth'])
->inject('utopia')
->inject('request')
->inject('project')
->action(function (App $utopia, Request $request, Document $project) {
// Http::init()
// ->groups(['auth'])
// ->inject('utopia')
// ->inject('request')
// ->inject('project')
// ->action(function (Http $utopia, Request $request, Document $project) {
$route = $utopia->getRoute();
// $route = $utopia->getRoute();
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
$isAppUser = Auth::isAppUser(Authorization::getRoles());
// $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
// $isAppUser = Auth::isAppUser(Authorization::getRoles());
if ($isAppUser || $isPrivilegedUser) { // Skip limits for app and console devs
return;
}
// if ($isAppUser || $isPrivilegedUser) { // Skip limits for app and console devs
// return;
// }
$auths = $project->getAttribute('auths', []);
switch ($route->getLabel('auth.type', '')) {
case 'emailPassword':
if (($auths['emailPassword'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email / Password authentication is disabled for this project');
}
break;
// $auths = $project->getAttribute('auths', []);
// switch ($route->getLabel('auth.type', '')) {
// case 'emailPassword':
// if (($auths['emailPassword'] ?? true) === false) {
// throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email / Password authentication is disabled for this project');
// }
// break;
case 'magic-url':
if ($project->getAttribute('usersAuthMagicURL', true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Magic URL authentication is disabled for this project');
}
break;
// case 'magic-url':
// if ($project->getAttribute('usersAuthMagicURL', true) === false) {
// throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Magic URL authentication is disabled for this project');
// }
// break;
case 'anonymous':
if (($auths['anonymous'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Anonymous authentication is disabled for this project');
}
break;
// case 'anonymous':
// if (($auths['anonymous'] ?? true) === false) {
// throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Anonymous authentication is disabled for this project');
// }
// break;
case 'invites':
if (($auths['invites'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Invites authentication is disabled for this project');
}
break;
// case 'invites':
// if (($auths['invites'] ?? true) === false) {
// throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Invites authentication is disabled for this project');
// }
// break;
case 'jwt':
if (($auths['JWT'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'JWT authentication is disabled for this project');
}
break;
// case 'jwt':
// if (($auths['JWT'] ?? true) === false) {
// throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'JWT authentication is disabled for this project');
// }
// break;
default:
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');
break;
}
});
// default:
// throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');
// break;
// }
// });
/**
* Limit user session
@@ -320,14 +320,14 @@ App::init()
* Delete older sessions if the number of sessions have crossed
* the session limit set for the project
*/
App::shutdown()
Http::shutdown()
->groups(['session'])
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('dbForProject')
->action(function (App $utopia, Request $request, Response $response, Document $project, Database $dbForProject) {
->action(function (Http $utopia, Request $request, Response $response, Document $project, Database $dbForProject) {
$sessionLimit = $project->getAttribute('auths', [])['maxSessions'] ?? APP_LIMIT_USER_SESSIONS_DEFAULT;
$session = $response->getPayload();
$userId = $session['userId'] ?? '';
@@ -353,7 +353,7 @@ App::shutdown()
$dbForProject->deleteCachedDocument('users', $userId);
});
App::shutdown()
Http::shutdown()
->groups(['api'])
->inject('utopia')
->inject('request')
@@ -369,7 +369,7 @@ App::shutdown()
->inject('queueForFunctions')
->inject('mode')
->inject('dbForConsole')
->action(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, Database $dbForProject, Func $queueForFunctions, string $mode, Database $dbForConsole) use ($parseLabel) {
->action(function (Http $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, Database $dbForProject, Func $queueForFunctions, string $mode, Database $dbForConsole) use ($parseLabel) {
$responsePayload = $response->getPayload();
@@ -523,7 +523,7 @@ App::shutdown()
}
if (
App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled'
Http::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled'
&& $project->getId()
&& !empty($route->getLabel('sdk.namespace', null))
) { // Don't calculate console usage on admin mode
+3 -3
View File
@@ -2,17 +2,17 @@
use Appwrite\Auth\Auth;
use Appwrite\Utopia\Request;
use Utopia\App;
use Utopia\Http\Http;
use Appwrite\Extend\Exception;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
App::init()
Http::init()
->groups(['auth'])
->inject('utopia')
->inject('request')
->inject('project')
->action(function (App $utopia, Request $request, Document $project) {
->action(function (Http $utopia, Request $request, Document $project) {
$route = $utopia->match($request);
+3 -3
View File
@@ -2,9 +2,9 @@
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Http\Http;
App::init()
Http::init()
->groups(['web'])
->inject('request')
->inject('response')
@@ -16,7 +16,7 @@ App::init()
;
});
App::get('/console/*')
Http::get('/console/*')
->alias('/')
->alias('auth/*')
->alias('/invite')
+9 -2
View File
@@ -1,15 +1,22 @@
<?php
use Appwrite\Utopia\Response;
use Utopia\App;
use Swoole\Database\PDOProxy;
use Utopia\Http\Http;
use Utopia\Config\Config;
App::get('/versions')
Http::get('/versions')
->desc('Get Version')
->groups(['home', 'web'])
->label('scope', 'public')
->inject('response')
// ->inject('c')
->action(function (Response $response) {
// $statement = $c->prepare('SELECT 1+1');
// $statement->execute();
// $res = $statement->fetchAll()[0][0];
// \var_dump($res);
$platforms = Config::getParam('platforms');
$versions = [
+278 -289
View File
@@ -2,12 +2,11 @@
require_once __DIR__ . '/../vendor/autoload.php';
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Swoole\Process;
use Swoole\Http\Server;
use Swoole\Http\Request as SwooleRequest;
use Swoole\Http\Response as SwooleResponse;
use Utopia\App;
use Utopia\Http\Adapter\Swoole\Server;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Helpers\ID;
@@ -18,19 +17,19 @@ use Utopia\Audit\Audit;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Swoole\Files;
use Appwrite\Utopia\Request;
use Utopia\Logger\Log;
use Utopia\Logger\Log\User;
use Utopia\Pools\Group;
$http = new Server("0.0.0.0", App::getEnv('PORT', 80));
use function Swoole\Coroutine\run;
$http = new Server("0.0.0.0", Http::getEnv('PORT', 80));
$payloadSize = 6 * (1024 * 1024); // 6MB
$workerNumber = swoole_cpu_num() * intval(App::getEnv('_APP_WORKER_PER_CORE', 6));
$workerNumber = swoole_cpu_num() * intval(Http::getEnv('_APP_WORKER_PER_CORE', 6));
$http
->set([
->setConfig([
'worker_num' => $workerNumber,
'open_http2_protocol' => true,
// 'document_root' => __DIR__.'/../public',
@@ -41,295 +40,285 @@ $http
'buffer_output_size' => $payloadSize,
]);
$http->on('WorkerStart', function ($server, $workerId) {
Console::success('Worker ' . ++$workerId . ' started successfully');
});
Http::onWorkerStart()
->inject('workerId')
->action(function ($workerId) {
Console::success('Worker ' . ++$workerId . ' started successfully');
});
$http->on('BeforeReload', function ($server, $workerId) {
Console::success('Starting reload...');
});
$http->on('AfterReload', function ($server, $workerId) {
Console::success('Reload completed...');
});
Files::load(__DIR__ . '/../console');
include __DIR__ . '/controllers/general.php';
$http->on('start', function (Server $http) use ($payloadSize, $register) {
$app = new App('UTC');
Http::onStart()
->inject('register')
->inject('utopia')
->inject('server')
->action(function ($register, $app, $http) use ($payloadSize) {
go(function () use ($register, $app) {
$pools = $register->get('pools');
/** @var Group $pools */
Http::setResource('pools', fn () => $pools);
go(function () use ($register, $app) {
$pools = $register->get('pools');
/** @var Group $pools */
App::setResource('pools', fn () => $pools);
// wait for database to be ready
$attempts = 0;
$max = 10;
$sleep = 1;
// wait for database to be ready
$attempts = 0;
$max = 10;
$sleep = 1;
do {
try {
$attempts++;
$dbForConsole = $app->getResource('dbForConsole');
/** @var Utopia\Database\Database $dbForConsole */
break; // leave the do-while if successful
} catch (\Exception $e) {
Console::warning("Database not ready. Retrying connection ({$attempts})...");
if ($attempts >= $max) {
throw new \Exception('Failed to connect to database: ' . $e->getMessage());
do {
try {
$attempts++;
$dbForConsole = $app->getResource('dbForConsole');
/** @var Utopia\Database\Database $dbForConsole */
break; // leave the do-while if successful
} catch (\Exception $e) {
Console::warning("Database not ready. Retrying connection ({$attempts})...");
if ($attempts >= $max) {
throw new \Exception('Failed to connect to database: ' . $e->getMessage());
}
sleep($sleep);
}
sleep($sleep);
}
} while ($attempts < $max);
} while ($attempts < $max);
Console::success('[Setup] - Server database init started...');
Console::success('[Setup] - Server database init started...');
try {
Console::success('[Setup] - Creating database: appwrite...');
$dbForConsole->create();
} catch (\Exception $e) {
Console::success('[Setup] - Skip: metadata table already exists');
}
if ($dbForConsole->getCollection(Audit::COLLECTION)->isEmpty()) {
$audit = new Audit($dbForConsole);
$audit->setup();
}
if ($dbForConsole->getCollection(TimeLimit::COLLECTION)->isEmpty()) {
$adapter = new TimeLimit("", 0, 1, $dbForConsole);
$adapter->setup();
}
/** @var array $collections */
$collections = Config::getParam('collections', []);
$consoleCollections = $collections['console'];
foreach ($consoleCollections as $key => $collection) {
if (($collection['$collection'] ?? '') !== Database::METADATA) {
continue;
}
if (!$dbForConsole->getCollection($key)->isEmpty()) {
continue;
}
Console::success('[Setup] - Creating collection: ' . $collection['$id'] . '...');
$attributes = [];
$indexes = [];
foreach ($collection['attributes'] as $attribute) {
$attributes[] = new Document([
'$id' => ID::custom($attribute['$id']),
'type' => $attribute['type'],
'size' => $attribute['size'],
'required' => $attribute['required'],
'signed' => $attribute['signed'],
'array' => $attribute['array'],
'filters' => $attribute['filters'],
'default' => $attribute['default'] ?? null,
'format' => $attribute['format'] ?? ''
]);
}
foreach ($collection['indexes'] as $index) {
$indexes[] = new Document([
'$id' => ID::custom($index['$id']),
'type' => $index['type'],
'attributes' => $index['attributes'],
'lengths' => $index['lengths'],
'orders' => $index['orders'],
]);
}
$dbForConsole->createCollection($key, $attributes, $indexes);
}
if ($dbForConsole->getDocument('buckets', 'default')->isEmpty() && !$dbForConsole->exists($dbForConsole->getDefaultDatabase(), 'bucket_1')) {
Console::success('[Setup] - Creating default bucket...');
$dbForConsole->createDocument('buckets', new Document([
'$id' => ID::custom('default'),
'$collection' => ID::custom('buckets'),
'name' => 'Default',
'maximumFileSize' => (int) Http::getEnv('_APP_STORAGE_LIMIT', 0), // 10MB
'allowedFileExtensions' => [],
'enabled' => true,
'compression' => 'gzip',
'encryption' => true,
'antivirus' => true,
'fileSecurity' => true,
'$permissions' => [
Permission::create(Role::any()),
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
'search' => 'buckets Default',
]));
$bucket = $dbForConsole->getDocument('buckets', 'default');
Console::success('[Setup] - Creating files collection for default bucket...');
$files = $collections['buckets']['files'] ?? [];
if (empty($files)) {
throw new Exception('Files collection is not configured.');
}
$attributes = [];
$indexes = [];
foreach ($files['attributes'] as $attribute) {
$attributes[] = new Document([
'$id' => ID::custom($attribute['$id']),
'type' => $attribute['type'],
'size' => $attribute['size'],
'required' => $attribute['required'],
'signed' => $attribute['signed'],
'array' => $attribute['array'],
'filters' => $attribute['filters'],
'default' => $attribute['default'] ?? null,
'format' => $attribute['format'] ?? ''
]);
}
foreach ($files['indexes'] as $index) {
$indexes[] = new Document([
'$id' => ID::custom($index['$id']),
'type' => $index['type'],
'attributes' => $index['attributes'],
'lengths' => $index['lengths'],
'orders' => $index['orders'],
]);
}
$dbForConsole->createCollection('bucket_' . $bucket->getInternalId(), $attributes, $indexes);
}
$pools->reclaim();
Console::success('[Setup] - Server database init completed...');
});
Console::success('Server started successfully (max payload is ' . number_format($payloadSize) . ' bytes)');
// listen ctrl + c
Process::signal(2, function () use ($http) {
Console::log('Stop by Ctrl+C');
$http->shutdown();
});
});
Http::onRequest()
->inject('register')
->inject('swooleRequest')
->inject('swooleResponse')
->inject('utopia')
->inject('context')
->action(function ($register, $request, $response, $app, $context) {
$pools = $register->get('pools');
Http::setResource('pools', fn () => $pools);
$request = new Request($request);
$response = new Response($response);
Http::setResource('request', fn() => $request, [], $context);
Http::setResource('response', fn() => $response, [], $context);
try {
Console::success('[Setup] - Creating database: appwrite...');
$dbForConsole->create();
} catch (\Exception $e) {
Console::success('[Setup] - Skip: metadata table already exists');
Authorization::cleanRoles();
Authorization::setRole(Role::any()->toString());
} catch (\Throwable $th) {
$version = Http::getEnv('_APP_VERSION', 'UNKNOWN');
$logger = $app->getResource("logger");
if ($logger) {
try {
/** @var Utopia\Database\Document $user */
$user = $app->getResource('user');
} catch (\Throwable $_th) {
// All good, user is optional information for logger
}
$loggerBreadcrumbs = $app->getResource("loggerBreadcrumbs");
$route = $app->getRoute();
$log = new Utopia\Logger\Log();
if (isset($user) && !$user->isEmpty()) {
$log->setUser(new User($user->getId()));
}
$log->setNamespace("http");
$log->setServer(\gethostname());
$log->setVersion($version);
$log->setType(Log::TYPE_ERROR);
$log->setMessage($th->getMessage());
$log->addTag('method', $route->getMethod());
$log->addTag('url', $route->getPath());
$log->addTag('verboseType', get_class($th));
$log->addTag('code', $th->getCode());
// $log->addTag('projectId', $project->getId()); // TODO: Figure out how to get ProjectID, if it becomes relevant
$log->addTag('hostname', $request->getHostname());
$log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', '')));
$log->addExtra('file', $th->getFile());
$log->addExtra('line', $th->getLine());
$log->addExtra('trace', $th->getTraceAsString());
$log->addExtra('detailedTrace', $th->getTrace());
$log->addExtra('roles', Authorization::getRoles());
$action = $route->getLabel("sdk.namespace", "UNKNOWN_NAMESPACE") . '.' . $route->getLabel("sdk.method", "UNKNOWN_METHOD");
$log->setAction($action);
$isProduction = Http::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
foreach ($loggerBreadcrumbs as $loggerBreadcrumb) {
$log->addBreadcrumb($loggerBreadcrumb);
}
$responseCode = $logger->addLog($log);
Console::info('Log pushed with status code: ' . $responseCode);
}
Console::error('[Error] Type: ' . get_class($th));
Console::error('[Error] Message: ' . $th->getMessage());
Console::error('[Error] File: ' . $th->getFile());
Console::error('[Error] Line: ' . $th->getLine());
$response->setStatusCode(500);
$output = ((Http::isDevelopment())) ? [
'message' => 'Error: ' . $th->getMessage(),
'code' => 500,
'file' => $th->getFile(),
'line' => $th->getLine(),
'trace' => $th->getTrace(),
'version' => $version,
] : [
'message' => 'Error: Server Error',
'code' => 500,
'version' => $version,
];
$response->end(\json_encode($output));
} finally {
// $pools->reclaim();
}
});
if ($dbForConsole->getCollection(Audit::COLLECTION)->isEmpty()) {
$audit = new Audit($dbForConsole);
$audit->setup();
}
if ($dbForConsole->getCollection(TimeLimit::COLLECTION)->isEmpty()) {
$adapter = new TimeLimit("", 0, 1, $dbForConsole);
$adapter->setup();
}
/** @var array $collections */
$collections = Config::getParam('collections', []);
$consoleCollections = $collections['console'];
foreach ($consoleCollections as $key => $collection) {
if (($collection['$collection'] ?? '') !== Database::METADATA) {
continue;
}
if (!$dbForConsole->getCollection($key)->isEmpty()) {
continue;
}
Console::success('[Setup] - Creating collection: ' . $collection['$id'] . '...');
$attributes = [];
$indexes = [];
foreach ($collection['attributes'] as $attribute) {
$attributes[] = new Document([
'$id' => ID::custom($attribute['$id']),
'type' => $attribute['type'],
'size' => $attribute['size'],
'required' => $attribute['required'],
'signed' => $attribute['signed'],
'array' => $attribute['array'],
'filters' => $attribute['filters'],
'default' => $attribute['default'] ?? null,
'format' => $attribute['format'] ?? ''
]);
}
foreach ($collection['indexes'] as $index) {
$indexes[] = new Document([
'$id' => ID::custom($index['$id']),
'type' => $index['type'],
'attributes' => $index['attributes'],
'lengths' => $index['lengths'],
'orders' => $index['orders'],
]);
}
$dbForConsole->createCollection($key, $attributes, $indexes);
}
if ($dbForConsole->getDocument('buckets', 'default')->isEmpty() && !$dbForConsole->exists($dbForConsole->getDefaultDatabase(), 'bucket_1')) {
Console::success('[Setup] - Creating default bucket...');
$dbForConsole->createDocument('buckets', new Document([
'$id' => ID::custom('default'),
'$collection' => ID::custom('buckets'),
'name' => 'Default',
'maximumFileSize' => (int) App::getEnv('_APP_STORAGE_LIMIT', 0), // 10MB
'allowedFileExtensions' => [],
'enabled' => true,
'compression' => 'gzip',
'encryption' => true,
'antivirus' => true,
'fileSecurity' => true,
'$permissions' => [
Permission::create(Role::any()),
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
'search' => 'buckets Default',
]));
$bucket = $dbForConsole->getDocument('buckets', 'default');
Console::success('[Setup] - Creating files collection for default bucket...');
$files = $collections['buckets']['files'] ?? [];
if (empty($files)) {
throw new Exception('Files collection is not configured.');
}
$attributes = [];
$indexes = [];
foreach ($files['attributes'] as $attribute) {
$attributes[] = new Document([
'$id' => ID::custom($attribute['$id']),
'type' => $attribute['type'],
'size' => $attribute['size'],
'required' => $attribute['required'],
'signed' => $attribute['signed'],
'array' => $attribute['array'],
'filters' => $attribute['filters'],
'default' => $attribute['default'] ?? null,
'format' => $attribute['format'] ?? ''
]);
}
foreach ($files['indexes'] as $index) {
$indexes[] = new Document([
'$id' => ID::custom($index['$id']),
'type' => $index['type'],
'attributes' => $index['attributes'],
'lengths' => $index['lengths'],
'orders' => $index['orders'],
]);
}
$dbForConsole->createCollection('bucket_' . $bucket->getInternalId(), $attributes, $indexes);
}
$pools->reclaim();
Console::success('[Setup] - Server database init completed...');
});
Console::success('Server started successfully (max payload is ' . number_format($payloadSize) . ' bytes)');
Console::info("Master pid {$http->master_pid}, manager pid {$http->manager_pid}");
// listen ctrl + c
Process::signal(2, function () use ($http) {
Console::log('Stop by Ctrl+C');
$http->shutdown();
});
});
$http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) use ($register) {
App::setResource('swooleRequest', fn () => $swooleRequest);
App::setResource('swooleResponse', fn () => $swooleResponse);
$request = new Request($swooleRequest);
$response = new Response($swooleResponse);
if (Files::isFileLoaded($request->getURI())) {
$time = (60 * 60 * 24 * 365 * 2); // 45 days cache
$response
->setContentType(Files::getFileMimeType($request->getURI()))
->addHeader('Cache-Control', 'public, max-age=' . $time)
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time) . ' GMT') // 45 days cache
->send(Files::getFileContents($request->getURI()));
return;
}
$app = new App('UTC');
$pools = $register->get('pools');
App::setResource('pools', fn () => $pools);
try {
Authorization::cleanRoles();
Authorization::setRole(Role::any()->toString());
$app->run($request, $response);
} catch (\Throwable $th) {
$version = App::getEnv('_APP_VERSION', 'UNKNOWN');
$logger = $app->getResource("logger");
if ($logger) {
try {
/** @var Utopia\Database\Document $user */
$user = $app->getResource('user');
} catch (\Throwable $_th) {
// All good, user is optional information for logger
}
$loggerBreadcrumbs = $app->getResource("loggerBreadcrumbs");
$route = $app->getRoute();
$log = new Utopia\Logger\Log();
if (isset($user) && !$user->isEmpty()) {
$log->setUser(new User($user->getId()));
}
$log->setNamespace("http");
$log->setServer(\gethostname());
$log->setVersion($version);
$log->setType(Log::TYPE_ERROR);
$log->setMessage($th->getMessage());
$log->addTag('method', $route->getMethod());
$log->addTag('url', $route->getPath());
$log->addTag('verboseType', get_class($th));
$log->addTag('code', $th->getCode());
// $log->addTag('projectId', $project->getId()); // TODO: Figure out how to get ProjectID, if it becomes relevant
$log->addTag('hostname', $request->getHostname());
$log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', '')));
$log->addExtra('file', $th->getFile());
$log->addExtra('line', $th->getLine());
$log->addExtra('trace', $th->getTraceAsString());
$log->addExtra('detailedTrace', $th->getTrace());
$log->addExtra('roles', Authorization::getRoles());
$action = $route->getLabel("sdk.namespace", "UNKNOWN_NAMESPACE") . '.' . $route->getLabel("sdk.method", "UNKNOWN_METHOD");
$log->setAction($action);
$isProduction = App::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
foreach ($loggerBreadcrumbs as $loggerBreadcrumb) {
$log->addBreadcrumb($loggerBreadcrumb);
}
$responseCode = $logger->addLog($log);
Console::info('Log pushed with status code: ' . $responseCode);
}
Console::error('[Error] Type: ' . get_class($th));
Console::error('[Error] Message: ' . $th->getMessage());
Console::error('[Error] File: ' . $th->getFile());
Console::error('[Error] Line: ' . $th->getLine());
$swooleResponse->setStatusCode(500);
$output = ((App::isDevelopment())) ? [
'message' => 'Error: ' . $th->getMessage(),
'code' => 500,
'file' => $th->getFile(),
'line' => $th->getLine(),
'trace' => $th->getTrace(),
'version' => $version,
] : [
'message' => 'Error: Server Error',
'code' => 500,
'version' => $version,
];
$swooleResponse->end(\json_encode($output));
} finally {
$pools->reclaim();
}
});
$http->start();
run(function () use ($http) {
$app = new Http($http, 'UTC');
$app->loadFiles(__DIR__ . '/../console');
$app->start();
});
+147 -130
View File
@@ -33,7 +33,7 @@ use Appwrite\Network\Validator\Origin;
use Appwrite\OpenSSL\OpenSSL;
use Appwrite\URL\URL as AppwriteURL;
use Appwrite\Usage\Stats;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Logger\Logger;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Cache\Cache;
@@ -78,10 +78,10 @@ use Utopia\Queue;
use Utopia\Queue\Connection;
use Utopia\Storage\Storage;
use Utopia\VCS\Adapter\Git\GitHub as VcsGitHub;
use Utopia\Validator\Range;
use Utopia\Validator\IP;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\Range;
use Utopia\Http\Validator\IP;
use Utopia\Http\Validator\URL;
use Utopia\Http\Validator\WhiteList;
const APP_NAME = 'Appwrite';
const APP_DOMAIN = 'appwrite.io';
@@ -225,7 +225,7 @@ const METRIC_NETWORK_OUTBOUND = 'network.outbound';
$register = new Registry();
App::setMode(App::getEnv('_APP_ENV', App::MODE_TYPE_PRODUCTION));
Http::setMode(Http::getEnv('_APP_ENV', Http::MODE_TYPE_PRODUCTION));
/*
* ENV vars
@@ -259,12 +259,12 @@ Config::load('storage-mimes', __DIR__ . '/config/storage/mimes.php');
Config::load('storage-inputs', __DIR__ . '/config/storage/inputs.php');
Config::load('storage-outputs', __DIR__ . '/config/storage/outputs.php');
$user = App::getEnv('_APP_REDIS_USER', '');
$pass = App::getEnv('_APP_REDIS_PASS', '');
$user = Http::getEnv('_APP_REDIS_USER', '');
$pass = Http::getEnv('_APP_REDIS_PASS', '');
if (!empty($user) || !empty($pass)) {
Resque::setBackend('redis://' . $user . ':' . $pass . '@' . App::getEnv('_APP_REDIS_HOST', '') . ':' . App::getEnv('_APP_REDIS_PORT', ''));
Resque::setBackend('redis://' . $user . ':' . $pass . '@' . Http::getEnv('_APP_REDIS_HOST', '') . ':' . Http::getEnv('_APP_REDIS_PORT', ''));
} else {
Resque::setBackend(App::getEnv('_APP_REDIS_HOST', '') . ':' . App::getEnv('_APP_REDIS_PORT', ''));
Resque::setBackend(Http::getEnv('_APP_REDIS_HOST', '') . ':' . Http::getEnv('_APP_REDIS_PORT', ''));
}
/**
@@ -320,8 +320,7 @@ Database::addFilter(
if (isset($formatOptions['min']) || isset($formatOptions['max'])) {
$attribute
->setAttribute('min', $formatOptions['min'])
->setAttribute('max', $formatOptions['max'])
;
->setAttribute('max', $formatOptions['max']);
}
return $value;
@@ -430,7 +429,7 @@ Database::addFilter(
return null;
},
function (mixed $value, Document $document, Database $database) {
return Authorization::skip(fn() => $database
return Authorization::skip(fn () => $database
->find('tokens', [
Query::equal('userInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
@@ -444,7 +443,7 @@ Database::addFilter(
return null;
},
function (mixed $value, Document $document, Database $database) {
return Authorization::skip(fn() => $database
return Authorization::skip(fn () => $database
->find('memberships', [
Query::equal('userInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
@@ -470,7 +469,7 @@ Database::addFilter(
Database::addFilter(
'encrypt',
function (mixed $value) {
$key = App::getEnv('_APP_OPENSSL_KEY_V1');
$key = Http::getEnv('_APP_OPENSSL_KEY_V1');
$iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM));
$tag = null;
@@ -487,7 +486,7 @@ Database::addFilter(
return null;
}
$value = json_decode($value, true);
$key = App::getEnv('_APP_OPENSSL_KEY_V' . $value['version']);
$key = Http::getEnv('_APP_OPENSSL_KEY_V' . $value['version']);
return OpenSSL::decrypt($value['data'], $value['method'], $key, 0, hex2bin($value['iv']), hex2bin($value['tag']));
}
@@ -571,8 +570,8 @@ Structure::addFormat(APP_DATABASE_ATTRIBUTE_FLOAT_RANGE, function ($attribute) {
*/
$register->set('logger', function () {
// Register error logger
$providerName = App::getEnv('_APP_LOGGING_PROVIDER', '');
$providerConfig = App::getEnv('_APP_LOGGING_CONFIG', '');
$providerName = Http::getEnv('_APP_LOGGING_PROVIDER', '');
$providerConfig = Http::getEnv('_APP_LOGGING_CONFIG', '');
if (empty($providerName) || empty($providerConfig)) {
return null;
@@ -591,60 +590,60 @@ $register->set('pools', function () {
$fallbackForDB = 'db_main=' . AppwriteURL::unparse([
'scheme' => 'mariadb',
'host' => App::getEnv('_APP_DB_HOST', 'mariadb'),
'port' => App::getEnv('_APP_DB_PORT', '3306'),
'user' => App::getEnv('_APP_DB_USER', ''),
'pass' => App::getEnv('_APP_DB_PASS', ''),
'path' => App::getEnv('_APP_DB_SCHEMA', ''),
'host' => Http::getEnv('_APP_DB_HOST', 'mariadb'),
'port' => Http::getEnv('_APP_DB_PORT', '3306'),
'user' => Http::getEnv('_APP_DB_USER', ''),
'pass' => Http::getEnv('_APP_DB_PASS', ''),
'path' => Http::getEnv('_APP_DB_SCHEMA', ''),
]);
$fallbackForRedis = 'redis_main=' . AppwriteURL::unparse([
'scheme' => 'redis',
'host' => App::getEnv('_APP_REDIS_HOST', 'redis'),
'port' => App::getEnv('_APP_REDIS_PORT', '6379'),
'user' => App::getEnv('_APP_REDIS_USER', ''),
'pass' => App::getEnv('_APP_REDIS_PASS', ''),
'host' => Http::getEnv('_APP_REDIS_HOST', 'redis'),
'port' => Http::getEnv('_APP_REDIS_PORT', '6379'),
'user' => Http::getEnv('_APP_REDIS_USER', ''),
'pass' => Http::getEnv('_APP_REDIS_PASS', ''),
]);
$connections = [
'console' => [
'type' => 'database',
'dsns' => App::getEnv('_APP_CONNECTIONS_DB_CONSOLE', $fallbackForDB),
'dsns' => Http::getEnv('_APP_CONNECTIONS_DB_CONSOLE', $fallbackForDB),
'multiple' => false,
'schemes' => ['mariadb', 'mysql'],
],
'database' => [
'type' => 'database',
'dsns' => App::getEnv('_APP_CONNECTIONS_DB_PROJECT', $fallbackForDB),
'dsns' => Http::getEnv('_APP_CONNECTIONS_DB_PROJECT', $fallbackForDB),
'multiple' => true,
'schemes' => ['mariadb', 'mysql'],
],
'queue' => [
'type' => 'queue',
'dsns' => App::getEnv('_APP_CONNECTIONS_QUEUE', $fallbackForRedis),
'dsns' => Http::getEnv('_APP_CONNECTIONS_QUEUE', $fallbackForRedis),
'multiple' => false,
'schemes' => ['redis'],
],
'pubsub' => [
'type' => 'pubsub',
'dsns' => App::getEnv('_APP_CONNECTIONS_PUBSUB', $fallbackForRedis),
'dsns' => Http::getEnv('_APP_CONNECTIONS_PUBSUB', $fallbackForRedis),
'multiple' => false,
'schemes' => ['redis'],
],
'cache' => [
'type' => 'cache',
'dsns' => App::getEnv('_APP_CONNECTIONS_CACHE', $fallbackForRedis),
'dsns' => Http::getEnv('_APP_CONNECTIONS_CACHE', $fallbackForRedis),
'multiple' => true,
'schemes' => ['redis'],
],
];
$maxConnections = App::getEnv('_APP_CONNECTIONS_MAX', 151);
$instanceConnections = $maxConnections / App::getEnv('_APP_POOL_CLIENTS', 14);
$maxConnections = Http::getEnv('_APP_CONNECTIONS_MAX', 151);
$instanceConnections = $maxConnections / Http::getEnv('_APP_POOL_CLIENTS', 14);
$multiprocessing = App::getEnv('_APP_SERVER_MULTIPROCESS', 'disabled') === 'enabled';
$multiprocessing = Http::getEnv('_APP_SERVER_MULTIPROCESS', 'disabled') === 'enabled';
if ($multiprocessing) {
$workerCount = swoole_cpu_num() * intval(App::getEnv('_APP_WORKER_PER_CORE', 6));
$workerCount = swoole_cpu_num() * intval(Http::getEnv('_APP_WORKER_PER_CORE', 6));
} else {
$workerCount = 1;
}
@@ -700,7 +699,7 @@ $register->set('pools', function () {
PDO::ATTR_TIMEOUT => 3, // Seconds
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => App::isDevelopment() ? PDO::ERRMODE_WARNING : PDO::ERRMODE_SILENT, // If in production mode, warnings are not displayed
PDO::ATTR_ERRMODE => Http::isDevelopment() ? PDO::ERRMODE_WARNING : PDO::ERRMODE_SILENT, // If in production mode, warnings are not displayed
PDO::ATTR_EMULATE_PREPARES => true,
PDO::ATTR_STRINGIFY_FETCHES => true
));
@@ -773,9 +772,9 @@ $register->set('pools', function () {
$register->set('influxdb', function () {
// Register DB connection
$host = App::getEnv('_APP_INFLUXDB_HOST', '');
$port = App::getEnv('_APP_INFLUXDB_PORT', '');
// Register DB connection
$host = Http::getEnv('_APP_INFLUXDB_HOST', '');
$port = Http::getEnv('_APP_INFLUXDB_PORT', '');
if (empty($host) || empty($port)) {
return;
@@ -788,8 +787,8 @@ $register->set('influxdb', function () {
});
$register->set('statsd', function () {
// Register DB connection
$host = App::getEnv('_APP_STATSD_HOST', 'telegraf');
$port = App::getEnv('_APP_STATSD_PORT', 8125);
$host = Http::getEnv('_APP_STATSD_HOST', 'telegraf');
$port = Http::getEnv('_APP_STATSD_PORT', 8125);
$connection = new \Domnikl\Statsd\Connection\UdpSocket($host, $port);
$statsd = new \Domnikl\Statsd\Client($connection);
@@ -801,21 +800,21 @@ $register->set('smtp', function () {
$mail->isSMTP();
$username = App::getEnv('_APP_SMTP_USERNAME');
$password = App::getEnv('_APP_SMTP_PASSWORD');
$username = Http::getEnv('_APP_SMTP_USERNAME');
$password = Http::getEnv('_APP_SMTP_PASSWORD');
$mail->XMailer = 'Appwrite Mailer';
$mail->Host = App::getEnv('_APP_SMTP_HOST', 'smtp');
$mail->Port = App::getEnv('_APP_SMTP_PORT', 25);
$mail->Host = Http::getEnv('_APP_SMTP_HOST', 'smtp');
$mail->Port = Http::getEnv('_APP_SMTP_PORT', 25);
$mail->SMTPAuth = !empty($username) && !empty($password);
$mail->Username = $username;
$mail->Password = $password;
$mail->SMTPSecure = App::getEnv('_APP_SMTP_SECURE', '');
$mail->SMTPSecure = Http::getEnv('_APP_SMTP_SECURE', '');
$mail->SMTPAutoTLS = false;
$mail->CharSet = 'UTF-8';
$from = \urldecode(App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server'));
$email = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$from = \urldecode(Http::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server'));
$email = Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$mail->setFrom($email, $from);
$mail->addReplyTo($email, $from);
@@ -863,46 +862,46 @@ foreach ($locales as $locale) {
'method' => 'GET',
'user_agent' => \sprintf(
APP_USERAGENT,
App::getEnv('_APP_VERSION', 'UNKNOWN'),
App::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)
Http::getEnv('_APP_VERSION', 'UNKNOWN'),
Http::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)
),
'timeout' => 2,
],
]);
// Runtime Execution
App::setResource('logger', function ($register) {
Http::setResource('logger', function ($register) {
return $register->get('logger');
}, ['register']);
App::setResource('loggerBreadcrumbs', function () {
Http::setResource('loggerBreadcrumbs', function () {
return [];
});
App::setResource('register', fn() => $register);
App::setResource('locale', fn() => new Locale(App::getEnv('_APP_LOCALE', 'en')));
Http::setResource('register', fn () => $register);
Http::setResource('locale', fn () => new Locale(Http::getEnv('_APP_LOCALE', 'en')));
App::setResource('localeCodes', function () {
return array_map(fn($locale) => $locale['code'], Config::getParam('locale-codes', []));
Http::setResource('localeCodes', function () {
return array_map(fn ($locale) => $locale['code'], Config::getParam('locale-codes', []));
});
// Queues
App::setResource('events', fn() => new Event('', ''));
App::setResource('audits', fn() => new Audit());
App::setResource('mails', fn() => new Mail());
App::setResource('deletes', fn() => new Delete());
App::setResource('database', fn() => new EventDatabase());
App::setResource('messaging', fn() => new Phone());
App::setResource('queue', function (Group $pools) {
Http::setResource('events', fn () => new Event('', ''));
Http::setResource('audits', fn () => new Audit());
Http::setResource('mails', fn () => new Mail());
Http::setResource('deletes', fn () => new Delete());
Http::setResource('database', fn () => new EventDatabase());
Http::setResource('messaging', fn () => new Phone());
Http::setResource('queue', function (Group $pools) {
return $pools->get('queue')->pop()->getResource();
}, ['pools']);
App::setResource('queueForFunctions', function (Connection $queue) {
Http::setResource('queueForFunctions', function (Connection $queue) {
return new Func($queue);
}, ['queue']);
App::setResource('usage', function ($register) {
Http::setResource('usage', function ($register) {
return new Stats($register->get('statsd'));
}, ['register']);
App::setResource('clients', function ($request, $console, $project) {
Http::setResource('clients', function ($request, $console, $project) {
$console->setAttribute('platforms', [ // Always allow current host
'$collection' => ID::custom('platforms'),
'name' => 'Current Host',
@@ -938,7 +937,7 @@ App::setResource('clients', function ($request, $console, $project) {
return $clients;
}, ['request', 'console', 'project']);
App::setResource('user', function ($mode, $project, $console, $request, $response, $dbForProject, $dbForConsole) {
Http::setResource('user', function ($mode, $project, $console, $request, $response, $dbForProject, $dbForConsole) {
/** @var Appwrite\Utopia\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Document $project */
@@ -961,7 +960,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
Auth::$cookieName, // Get sessions
$request->getCookie(Auth::$cookieName . '_legacy', '')
)
);// Get fallback session from old clients (no SameSite support)
); // Get fallback session from old clients (no SameSite support)
// Get fallback session from clients who block 3rd-party cookies
if ($response) {
@@ -1012,7 +1011,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
$authJWT = $request->getHeader('x-appwrite-jwt', '');
if (!empty($authJWT) && !$project->isEmpty()) { // JWT authentication
$jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.
$jwt = new JWT(Http::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway.
try {
$payload = $jwt->decode($authJWT);
@@ -1035,7 +1034,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
return $user;
}, ['mode', 'project', 'console', 'request', 'response', 'dbForProject', 'dbForConsole']);
App::setResource('project', function ($dbForConsole, $request, $console) {
Http::setResource('project', function ($dbForConsole, $request, $console) {
/** @var Appwrite\Utopia\Request $request */
/** @var Utopia\Database\Database $dbForConsole */
/** @var Utopia\Database\Document $console */
@@ -1046,12 +1045,12 @@ App::setResource('project', function ($dbForConsole, $request, $console) {
return $console;
}
$project = Authorization::skip(fn() => $dbForConsole->getDocument('projects', $projectId));
$project = Authorization::skip(fn () => $dbForConsole->getDocument('projects', $projectId));
return $project;
}, ['dbForConsole', 'request', 'console']);
App::setResource('console', function () {
Http::setResource('console', function () {
return new Document([
'$id' => ID::custom('console'),
'$internalId' => ID::custom('console'),
@@ -1077,21 +1076,21 @@ App::setResource('console', function () {
'legalAddress' => '',
'legalTaxId' => '',
'auths' => [
'invites' => App::getEnv('_APP_CONSOLE_INVITES', 'enabled') === 'enabled',
'limit' => (App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled') === 'enabled') ? 1 : 0, // limit signup to 1 user
'invites' => Http::getEnv('_APP_CONSOLE_INVITES', 'enabled') === 'enabled',
'limit' => (Http::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled') === 'enabled') ? 1 : 0, // limit signup to 1 user
'duration' => Auth::TOKEN_EXPIRATION_LOGIN_LONG, // 1 Year in seconds
],
'authWhitelistEmails' => (!empty(App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [],
'authWhitelistIPs' => (!empty(App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null)) : [],
'authWhitelistEmails' => (!empty(Http::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', Http::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [],
'authWhitelistIPs' => (!empty(Http::getEnv('_APP_CONSOLE_WHITELIST_IPS', null))) ? \explode(',', Http::getEnv('_APP_CONSOLE_WHITELIST_IPS', null)) : [],
'authProviders' => [
'githubEnabled' => true,
'githubSecret' => App::getEnv('_APP_CONSOLE_GITHUB_SECRET', ''),
'githubAppid' => App::getEnv('_APP_CONSOLE_GITHUB_APP_ID', '')
'githubSecret' => Http::getEnv('_APP_CONSOLE_GITHUB_SECRET', ''),
'githubAppid' => Http::getEnv('_APP_CONSOLE_GITHUB_APP_ID', '')
],
]);
}, []);
App::setResource('dbForProject', function (Group $pools, Database $dbForConsole, Cache $cache, Document $project) {
Http::setResource('dbForProject', function (Group $pools, Database $dbForConsole, Cache $cache, Document $project) {
if ($project->isEmpty() || $project->getId() === 'console') {
return $dbForConsole;
}
@@ -1099,8 +1098,7 @@ App::setResource('dbForProject', function (Group $pools, Database $dbForConsole,
$dbAdapter = $pools
->get($project->getAttribute('database'))
->pop()
->getResource()
;
->getResource();
$database = new Database($dbAdapter, $cache);
$database->setNamespace('_' . $project->getInternalId());
@@ -1108,12 +1106,11 @@ App::setResource('dbForProject', function (Group $pools, Database $dbForConsole,
return $database;
}, ['pools', 'dbForConsole', 'cache', 'project']);
App::setResource('dbForConsole', function (Group $pools, Cache $cache) {
Http::setResource('dbForConsole', function (Group $pools, Cache $cache) {
$dbAdapter = $pools
->get('console')
->pop()
->getResource()
;
->getResource();
$database = new Database($dbAdapter, $cache);
@@ -1122,7 +1119,7 @@ App::setResource('dbForConsole', function (Group $pools, Cache $cache) {
return $database;
}, ['pools', 'cache']);
App::setResource('getProjectDB', function (Group $pools, Database $dbForConsole, $cache) {
Http::setResource('getProjectDB', function (Group $pools, Database $dbForConsole, $cache) {
$databases = []; // TODO: @Meldiron This should probably be responsibility of utopia-php/pools
$getProjectDB = function (Document $project) use ($pools, $dbForConsole, $cache, &$databases) {
@@ -1155,7 +1152,7 @@ App::setResource('getProjectDB', function (Group $pools, Database $dbForConsole,
return $getProjectDB;
}, ['pools', 'dbForConsole', 'cache']);
App::setResource('cache', function (Group $pools) {
Http::setResource('cache', function (Group $pools) {
$list = Config::getParam('pools-cache', []);
$adapters = [];
@@ -1163,32 +1160,31 @@ App::setResource('cache', function (Group $pools) {
$adapters[] = $pools
->get($value)
->pop()
->getResource()
;
->getResource();
}
return new Cache(new Sharding($adapters));
}, ['pools']);
App::setResource('deviceLocal', function () {
Http::setResource('deviceLocal', function () {
return new Local();
});
App::setResource('deviceFiles', function ($project) {
Http::setResource('deviceFiles', function ($project) {
return getDevice(APP_STORAGE_UPLOADS . '/app-' . $project->getId());
}, ['project']);
App::setResource('deviceFunctions', function ($project) {
Http::setResource('deviceFunctions', function ($project) {
return getDevice(APP_STORAGE_FUNCTIONS . '/app-' . $project->getId());
}, ['project']);
App::setResource('deviceBuilds', function ($project) {
Http::setResource('deviceBuilds', function ($project) {
return getDevice(APP_STORAGE_BUILDS . '/app-' . $project->getId());
}, ['project']);
function getDevice($root): Device
{
$connection = App::getEnv('_APP_CONNECTIONS_STORAGE', '');
$connection = Http::getEnv('_APP_CONNECTIONS_STORAGE', '');
if (!empty($connection)) {
$acl = 'private';
@@ -1225,50 +1221,50 @@ function getDevice($root): Device
return new Local($root);
}
} else {
switch (strtolower(App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL) ?? '')) {
switch (strtolower(Http::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL) ?? '')) {
case Storage::DEVICE_LOCAL:
default:
return new Local($root);
case Storage::DEVICE_S3:
$s3AccessKey = App::getEnv('_APP_STORAGE_S3_ACCESS_KEY', '');
$s3SecretKey = App::getEnv('_APP_STORAGE_S3_SECRET', '');
$s3Region = App::getEnv('_APP_STORAGE_S3_REGION', '');
$s3Bucket = App::getEnv('_APP_STORAGE_S3_BUCKET', '');
$s3AccessKey = Http::getEnv('_APP_STORAGE_S3_ACCESS_KEY', '');
$s3SecretKey = Http::getEnv('_APP_STORAGE_S3_SECRET', '');
$s3Region = Http::getEnv('_APP_STORAGE_S3_REGION', '');
$s3Bucket = Http::getEnv('_APP_STORAGE_S3_BUCKET', '');
$s3Acl = 'private';
return new S3($root, $s3AccessKey, $s3SecretKey, $s3Bucket, $s3Region, $s3Acl);
case Storage::DEVICE_DO_SPACES:
$doSpacesAccessKey = App::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', '');
$doSpacesSecretKey = App::getEnv('_APP_STORAGE_DO_SPACES_SECRET', '');
$doSpacesRegion = App::getEnv('_APP_STORAGE_DO_SPACES_REGION', '');
$doSpacesBucket = App::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', '');
$doSpacesAccessKey = Http::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', '');
$doSpacesSecretKey = Http::getEnv('_APP_STORAGE_DO_SPACES_SECRET', '');
$doSpacesRegion = Http::getEnv('_APP_STORAGE_DO_SPACES_REGION', '');
$doSpacesBucket = Http::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', '');
$doSpacesAcl = 'private';
return new DOSpaces($root, $doSpacesAccessKey, $doSpacesSecretKey, $doSpacesBucket, $doSpacesRegion, $doSpacesAcl);
case Storage::DEVICE_BACKBLAZE:
$backblazeAccessKey = App::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', '');
$backblazeSecretKey = App::getEnv('_APP_STORAGE_BACKBLAZE_SECRET', '');
$backblazeRegion = App::getEnv('_APP_STORAGE_BACKBLAZE_REGION', '');
$backblazeBucket = App::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', '');
$backblazeAccessKey = Http::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', '');
$backblazeSecretKey = Http::getEnv('_APP_STORAGE_BACKBLAZE_SECRET', '');
$backblazeRegion = Http::getEnv('_APP_STORAGE_BACKBLAZE_REGION', '');
$backblazeBucket = Http::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', '');
$backblazeAcl = 'private';
return new Backblaze($root, $backblazeAccessKey, $backblazeSecretKey, $backblazeBucket, $backblazeRegion, $backblazeAcl);
case Storage::DEVICE_LINODE:
$linodeAccessKey = App::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', '');
$linodeSecretKey = App::getEnv('_APP_STORAGE_LINODE_SECRET', '');
$linodeRegion = App::getEnv('_APP_STORAGE_LINODE_REGION', '');
$linodeBucket = App::getEnv('_APP_STORAGE_LINODE_BUCKET', '');
$linodeAccessKey = Http::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', '');
$linodeSecretKey = Http::getEnv('_APP_STORAGE_LINODE_SECRET', '');
$linodeRegion = Http::getEnv('_APP_STORAGE_LINODE_REGION', '');
$linodeBucket = Http::getEnv('_APP_STORAGE_LINODE_BUCKET', '');
$linodeAcl = 'private';
return new Linode($root, $linodeAccessKey, $linodeSecretKey, $linodeBucket, $linodeRegion, $linodeAcl);
case Storage::DEVICE_WASABI:
$wasabiAccessKey = App::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', '');
$wasabiSecretKey = App::getEnv('_APP_STORAGE_WASABI_SECRET', '');
$wasabiRegion = App::getEnv('_APP_STORAGE_WASABI_REGION', '');
$wasabiBucket = App::getEnv('_APP_STORAGE_WASABI_BUCKET', '');
$wasabiAccessKey = Http::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', '');
$wasabiSecretKey = Http::getEnv('_APP_STORAGE_WASABI_SECRET', '');
$wasabiRegion = Http::getEnv('_APP_STORAGE_WASABI_REGION', '');
$wasabiBucket = Http::getEnv('_APP_STORAGE_WASABI_BUCKET', '');
$wasabiAcl = 'private';
return new Wasabi($root, $wasabiAccessKey, $wasabiSecretKey, $wasabiBucket, $wasabiRegion, $wasabiAcl);
}
}
}
App::setResource('mode', function ($request) {
Http::setResource('mode', function ($request) {
/** @var Appwrite\Utopia\Request $request */
/**
@@ -1279,18 +1275,18 @@ App::setResource('mode', function ($request) {
return $request->getParam('mode', $request->getHeader('x-appwrite-mode', APP_MODE_DEFAULT));
}, ['request']);
App::setResource('geodb', function ($register) {
Http::setResource('geodb', function ($register) {
/** @var Utopia\Registry\Registry $register */
return $register->get('geodb');
}, ['register']);
App::setResource('passwordsDictionary', function ($register) {
Http::setResource('passwordsDictionary', function ($register) {
/** @var Utopia\Registry\Registry $register */
return $register->get('passwordsDictionary');
}, ['register']);
App::setResource('sms', function () {
$dsn = new DSN(App::getEnv('_APP_SMS_PROVIDER'));
Http::setResource('sms', function () {
$dsn = new DSN(Http::getEnv('_APP_SMS_PROVIDER'));
$user = $dsn->getUser();
$secret = $dsn->getPassword();
@@ -1305,7 +1301,7 @@ App::setResource('sms', function () {
};
});
App::setResource('servers', function () {
Http::setResource('servers', function () {
$platforms = Config::getParam('platforms');
$server = $platforms[APP_PLATFORM_SERVER];
@@ -1316,11 +1312,11 @@ App::setResource('servers', function () {
return $languages;
});
App::setResource('promiseAdapter', function ($register) {
Http::setResource('promiseAdapter', function ($register) {
return $register->get('promiseAdapter');
}, ['register']);
App::setResource('schema', function ($utopia, $dbForProject) {
Http::setResource('schema', function ($utopia, $dbForProject) {
$complexity = function (int $complexity, array $args) {
$queries = Query::parseQueries($args['queries'] ?? []);
@@ -1331,7 +1327,7 @@ App::setResource('schema', function ($utopia, $dbForProject) {
};
$attributes = function (int $limit, int $offset) use ($dbForProject) {
$attrs = Authorization::skip(fn() => $dbForProject->find('attributes', [
$attrs = Authorization::skip(fn () => $dbForProject->find('attributes', [
Query::limit($limit),
Query::offset($offset),
]));
@@ -1361,7 +1357,7 @@ App::setResource('schema', function ($utopia, $dbForProject) {
$params = [
'list' => function (string $databaseId, string $collectionId, array $args) {
return [ 'queries' => $args['queries']];
return ['queries' => $args['queries']];
},
'create' => function (string $databaseId, string $collectionId, array $args) {
$id = $args['id'] ?? 'unique()';
@@ -1406,29 +1402,29 @@ App::setResource('schema', function ($utopia, $dbForProject) {
);
}, ['utopia', 'dbForProject']);
App::setResource('contributors', function () {
Http::setResource('contributors', function () {
$path = 'app/config/contributors.json';
$list = (file_exists($path)) ? json_decode(file_get_contents($path), true) : [];
return $list;
});
App::setResource('employees', function () {
Http::setResource('employees', function () {
$path = 'app/config/employees.json';
$list = (file_exists($path)) ? json_decode(file_get_contents($path), true) : [];
return $list;
});
App::setResource('heroes', function () {
Http::setResource('heroes', function () {
$path = 'app/config/heroes.json';
$list = (file_exists($path)) ? json_decode(file_get_contents($path), true) : [];
return $list;
});
App::setResource('gitHub', function (Cache $cache) {
Http::setResource('gitHub', function (Cache $cache) {
return new VcsGitHub($cache);
}, ['cache']);
App::setResource('requestTimestamp', function ($request) {
Http::setResource('requestTimestamp', function ($request) {
//TODO: Move this to the Request class itself
$timestampHeader = $request->getHeader('x-appwrite-timestamp');
$requestTimestamp = null;
@@ -1441,3 +1437,24 @@ App::setResource('requestTimestamp', function ($request) {
}
return $requestTimestamp;
}, ['request']);
$register->set('c', function () {
$group = new Group();
$pool = new Pool('s', 100, function () {
$pdo = new PDOProxy(function () {
return new PDO('mysql:host=mariadb;port=3306;dbname=appwrite;charset=utf8mb4', 'user', 'password');
});
return $pdo;
});
$group->add($pool);
return $group;
});
Http::setResource('c', function ($register) {
$pools = $register->get('c');
$s = $pools->get('s')->pop();
\var_dump($s->getId());
return $s->getResource();
}, ['register']);
+14 -14
View File
@@ -11,7 +11,7 @@ use Swoole\Table;
use Swoole\Timer;
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Role;
@@ -110,9 +110,9 @@ $stats->create();
$containerId = uniqid();
$statsDocument = null;
$workerNumber = swoole_cpu_num() * intval(App::getEnv('_APP_WORKER_PER_CORE', 6));
$workerNumber = swoole_cpu_num() * intval(Http::getEnv('_APP_WORKER_PER_CORE', 6));
$adapter = new Adapter\Swoole(port: App::getEnv('PORT', 80));
$adapter = new Adapter\Swoole(port: Http::getEnv('PORT', 80));
$adapter
->setPackageMaxLength(64000) // Default maximum Package Size (64kb)
->setWorkerNumber($workerNumber);
@@ -123,7 +123,7 @@ $logError = function (Throwable $error, string $action) use ($register) {
$logger = $register->get('logger');
if ($logger) {
$version = App::getEnv('_APP_VERSION', 'UNKNOWN');
$version = Http::getEnv('_APP_VERSION', 'UNKNOWN');
$log = new Log();
$log->setNamespace("realtime");
@@ -142,7 +142,7 @@ $logError = function (Throwable $error, string $action) use ($register) {
$log->setAction($action);
$isProduction = App::getEnv('_APP_ENV', 'development') === 'production';
$isProduction = Http::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
$responseCode = $logger->addLog($log);
@@ -344,7 +344,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
$receivers = $realtime->getSubscribers($event);
if (App::isDevelopment() && !empty($receivers)) {
if (Http::isDevelopment() && !empty($receivers)) {
Console::log("[Debug][Worker {$workerId}] Receivers: " . count($receivers));
Console::log("[Debug][Worker {$workerId}] Receivers Connection IDs: " . json_encode($receivers));
Console::log("[Debug][Worker {$workerId}] Event: " . $payload);
@@ -378,15 +378,15 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
});
$server->onOpen(function (int $connection, SwooleRequest $request) use ($server, $register, $stats, &$realtime, $logError) {
$app = new App('UTC');
$app = new Http('UTC');
$request = new Request($request);
$response = new Response(new SwooleResponse());
Console::info("Connection open (user: {$connection})");
App::setResource('pools', fn() => $register->get('pools'));
App::setResource('request', fn() => $request);
App::setResource('response', fn() => $response);
Http::setResource('pools', fn() => $register->get('pools'));
Http::setResource('request', fn() => $request);
Http::setResource('response', fn() => $response);
try {
/** @var \Utopia\Database\Document $project */
@@ -415,7 +415,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
$abuse = new Abuse($timeLimit);
if (App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled' && $abuse->check()) {
if (Http::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled' && $abuse->check()) {
throw new Exception('Too many requests', 1013);
}
@@ -474,7 +474,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
$server->send([$connection], json_encode($response));
$server->close($connection, $th->getCode());
if (App::isDevelopment()) {
if (Http::isDevelopment()) {
Console::error('[Error] Connection Error');
Console::error('[Error] Code: ' . $response['data']['code']);
Console::error('[Error] Message: ' . $response['data']['message']);
@@ -486,7 +486,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
$server->onMessage(function (int $connection, string $message) use ($server, $register, $realtime, $containerId) {
try {
$app = new App('UTC');
$app = new Http('UTC');
$response = new Response(new SwooleResponse());
$projectId = $realtime->connections[$connection]['projectId'];
$database = getConsoleDB();
@@ -509,7 +509,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re
$abuse = new Abuse($timeLimit);
if ($abuse->check() && App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled') {
if ($abuse->check() && Http::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled') {
throw new Exception('Too many messages', 1013);
}
+7 -7
View File
@@ -6,7 +6,7 @@ use Appwrite\Event\Func;
use Appwrite\Event\Usage;
use Appwrite\Usage\Stats;
use Swoole\Runtime;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Cache\Adapter\Sharding;
use Utopia\Cache\Cache;
use Utopia\CLI\CLI;
@@ -105,13 +105,13 @@ Server::setResource('pools', function ($register) {
$pools = $register->get('pools');
$connection = $pools->get('queue')->pop()->getResource();
$workerNumber = swoole_cpu_num() * intval(App::getEnv('_APP_WORKER_PER_CORE', 6));
$workerNumber = swoole_cpu_num() * intval(Http::getEnv('_APP_WORKER_PER_CORE', 6));
if (empty(App::getEnv('QUEUE'))) {
if (empty(Http::getEnv('QUEUE'))) {
throw new Exception('Please configure "QUEUE" environment variable.');
}
$adapter = new Swoole($connection, $workerNumber, App::getEnv('QUEUE'));
$adapter = new Swoole($connection, $workerNumber, Http::getEnv('QUEUE'));
$server = new Server($adapter);
$server
@@ -127,7 +127,7 @@ $server
->inject('logger')
->inject('log')
->action(function (Throwable $error, ?Logger $logger, Log $log) {
$version = App::getEnv('_APP_VERSION', 'UNKNOWN');
$version = Http::getEnv('_APP_VERSION', 'UNKNOWN');
if ($error instanceof PDOException) {
throw $error;
@@ -139,7 +139,7 @@ $server
$log->setVersion($version);
$log->setType(Log::TYPE_ERROR);
$log->setMessage($error->getMessage());
$log->setAction('appwrite-queue-' . App::getEnv('QUEUE'));
$log->setAction('appwrite-queue-' . Http::getEnv('QUEUE'));
$log->addTag('verboseType', get_class($error));
$log->addTag('code', $error->getCode());
$log->addExtra('file', $error->getFile());
@@ -148,7 +148,7 @@ $server
$log->addExtra('detailedTrace', $error->getTrace());
$log->addExtra('roles', Authorization::getRoles());
$isProduction = App::getEnv('_APP_ENV', 'development') === 'production';
$isProduction = Http::getEnv('_APP_ENV', 'development') === 'production';
$log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING);
$responseCode = $logger->addLog($log);
+8 -8
View File
@@ -10,7 +10,7 @@ use Executor\Executor;
use Appwrite\Usage\Stats;
use Appwrite\Vcs\Comment;
use Utopia\Database\DateTime;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Helpers\ID;
use Utopia\DSN\DSN;
@@ -40,7 +40,7 @@ class BuildsV1 extends Worker
public function init(): void
{
$this->executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST'));
$this->executor = new Executor(Http::getEnv('_APP_EXECUTOR_HOST'));
}
public function run(): void
@@ -151,8 +151,8 @@ class BuildsV1 extends Worker
if ($isVcsEnabled) {
$installation = $dbForConsole->getDocument('installations', $installationId);
$providerInstallationId = $installation->getAttribute('providerInstallationId');
$privateKey = App::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = App::getEnv('_APP_VCS_GITHUB_APP_ID');
$privateKey = Http::getEnv('_APP_VCS_GITHUB_PRIVATE_KEY');
$githubAppId = Http::getEnv('_APP_VCS_GITHUB_APP_ID');
$github->initializeVariables($providerInstallationId, $privateKey, $githubAppId);
}
@@ -260,7 +260,7 @@ class BuildsV1 extends Worker
}
$directorySize = $localDevice->getDirectorySize($tmpDirectory);
$functionsSizeLimit = (int) App::getEnv('_APP_FUNCTIONS_SIZE_LIMIT', '30000000');
$functionsSizeLimit = (int) Http::getEnv('_APP_FUNCTIONS_SIZE_LIMIT', '30000000');
if ($directorySize > $functionsSizeLimit) {
throw new Exception('Repository directory size should be less than ' . number_format($functionsSizeLimit / 1048576, 2) . ' MBs.');
}
@@ -503,7 +503,7 @@ class BuildsV1 extends Worker
);
/** Update usage stats */
if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
$statsd = $register->get('statsd');
$usage = new Stats($statsd);
$usage
@@ -549,8 +549,8 @@ class BuildsV1 extends Worker
$name = "{$functionName} ({$projectName})";
$protocol = App::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https';
$hostname = App::getEnv('_APP_DOMAIN');
$protocol = Http::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https';
$hostname = Http::getEnv('_APP_DOMAIN');
$functionId = $function->getId();
$projectId = $project->getId();
$providerTargetUrl = $protocol . '://' . $hostname . "/console/project-$projectId/functions/function-$functionId";
+7 -7
View File
@@ -7,7 +7,7 @@ use Appwrite\Messaging\Adapter\Realtime;
use Appwrite\Event\Event;
use Appwrite\Resque\Worker;
use Appwrite\Template\Template;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Database;
use Utopia\Database\Document;
@@ -91,7 +91,7 @@ class CertificatesV1 extends Worker
try {
// Email for alerts is required by LetsEncrypt
$email = App::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS');
$email = Http::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS');
if (empty($email)) {
throw new Exception('You must set a valid security email address (_APP_SYSTEM_SECURITY_EMAIL_ADDRESS) to issue an SSL certificate.');
}
@@ -189,7 +189,7 @@ class CertificatesV1 extends Worker
*/
private function getMainDomain(): ?string
{
$envDomain = App::getEnv('_APP_DOMAIN', '');
$envDomain = Http::getEnv('_APP_DOMAIN', '');
if (!empty($envDomain) && $envDomain !== 'localhost') {
return $envDomain;
}
@@ -221,7 +221,7 @@ class CertificatesV1 extends Worker
// TODO: Would be awesome to also support A/AAAA records here. Maybe dry run?
// Validate if domain target is properly configured
$target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));
$target = new Domain(Http::getEnv('_APP_DOMAIN_TARGET', ''));
if (!$target->isKnown() || $target->isTest()) {
throw new Exception('Unreachable CNAME target (' . $target->get() . '), please use a domain with a public suffix.');
@@ -281,7 +281,7 @@ class CertificatesV1 extends Worker
$stdout = '';
$stderr = '';
$staging = (App::isProduction()) ? '' : ' --dry-run';
$staging = (Http::isProduction()) ? '' : ' --dry-run';
$exit = Console::execute("certbot certonly -v --webroot --noninteractive --agree-tos{$staging}"
. " --email " . $email
. " --cert-name " . $folder
@@ -380,7 +380,7 @@ class CertificatesV1 extends Worker
// Send mail to administratore mail
$locale = new Locale(App::getEnv('_APP_LOCALE', 'en'));
$locale = new Locale(Http::getEnv('_APP_LOCALE', 'en'));
if (!$locale->getText('emails.sender') || !$locale->getText("emails.certificate.hello") || !$locale->getText("emails.certificate.subject") || !$locale->getText("emails.certificate.body") || !$locale->getText("emails.certificate.footer") || !$locale->getText("emails.certificate.thanks") || !$locale->getText("emails.certificate.signature")) {
$locale->setDefault('en');
}
@@ -409,7 +409,7 @@ class CertificatesV1 extends Worker
$body = $body->render();
$mail = new Mail();
$mail
->setRecipient(App::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS'))
->setRecipient(Http::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS'))
->setName('Appwrite Administrator')
->trigger();
}
+3 -3
View File
@@ -2,7 +2,7 @@
use Appwrite\Auth\Auth;
use Executor\Executor;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Cache\Adapter\Filesystem;
use Utopia\Cache\Cache;
use Utopia\Database\Database;
@@ -145,7 +145,7 @@ class DeletesV1 extends Worker
$this->listByGroup(
'schedules',
[
Query::equal('region', [App::getEnv('_APP_REGION', 'default')]),
Query::equal('region', [Http::getEnv('_APP_REGION', 'default')]),
Query::equal('resourceType', ['function']),
Query::lessThanEqual('resourceUpdatedAt', $datetime),
Query::equal('active', [false]),
@@ -949,7 +949,7 @@ class DeletesV1 extends Worker
protected function deleteRuntimes(?Document $function, Document $project)
{
$executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST'));
$executor = new Executor(Http::getEnv('_APP_EXECUTOR_HOST'));
$deleteByFunction = function (Document $function) use ($project, $executor) {
$this->listByGroup(
+3 -3
View File
@@ -10,7 +10,7 @@ use Appwrite\Messaging\Adapter\Realtime;
use Appwrite\Usage\Stats;
use Appwrite\Utopia\Response\Model\Execution;
use Executor\Executor;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Database;
@@ -183,7 +183,7 @@ Server::setResource('execute', function () {
try {
$version = $function->getAttribute('version', 'v2');
$command = $runtime['startCommand'];
$executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST'));
$executor = new Executor(Http::getEnv('_APP_EXECUTOR_HOST'));
$command = $version === 'v2' ? '' : 'cp /tmp/code.tar.gz /mnt/code/code.tar.gz && nohup helpers/start.sh "' . $command . '"';
$executionResponse = $executor->createExecution(
projectId: $project->getId(),
@@ -278,7 +278,7 @@ Server::setResource('execute', function () {
);
/** Update usage stats */
if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
if (Http::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') {
$usage = new Stats($statsd);
$usage
->setParam('projectId', $project->getId())
+2 -2
View File
@@ -2,7 +2,7 @@
use Appwrite\Resque\Worker;
use Appwrite\Template\Template;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use PHPMailer\PHPMailer\PHPMailer;
@@ -28,7 +28,7 @@ class MailsV1 extends Worker
$smtp = $this->args['smtp'];
if (empty($smtp) && empty(App::getEnv('_APP_SMTP_HOST'))) {
if (empty($smtp) && empty(Http::getEnv('_APP_SMTP_HOST'))) {
Console::info('Skipped mail processing. No SMTP configuration has been set.');
return;
}
+4 -4
View File
@@ -1,7 +1,7 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\DSN\DSN;
use Utopia\Messaging\Adapter;
@@ -30,7 +30,7 @@ class MessagingV1 extends Worker
public function init(): void
{
$dsn = new DSN(App::getEnv('_APP_SMS_PROVIDER'));
$dsn = new DSN(Http::getEnv('_APP_SMS_PROVIDER'));
$user = $dsn->getUser();
$secret = $dsn->getPassword();
@@ -44,12 +44,12 @@ class MessagingV1 extends Worker
default => null
};
$this->from = App::getEnv('_APP_SMS_FROM');
$this->from = Http::getEnv('_APP_SMS_FROM');
}
public function run(): void
{
if (empty(App::getEnv('_APP_SMS_PROVIDER'))) {
if (empty(Http::getEnv('_APP_SMS_PROVIDER'))) {
Console::info('Skipped sms processing. No Phone provider has been set.');
return;
}
+3 -3
View File
@@ -1,7 +1,7 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Document;
@@ -56,8 +56,8 @@ class WebhooksV1 extends Worker
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
\curl_setopt($ch, CURLOPT_USERAGENT, \sprintf(
APP_USERAGENT,
App::getEnv('_APP_VERSION', 'UNKNOWN'),
App::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)
Http::getEnv('_APP_VERSION', 'UNKNOWN'),
Http::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', APP_EMAIL_SECURITY)
));
\curl_setopt(
$ch,
+10 -6
View File
@@ -47,12 +47,13 @@
"utopia-php/analytics": "0.10.*",
"utopia-php/audit": "0.33.*",
"utopia-php/cache": "0.8.*",
"utopia-php/cli": "0.15.*",
"utopia-php/cli": "dev-feat-framework-v2 as 0.15.99",
"utopia-php/config": "0.2.*",
"utopia-php/database": "0.43.*",
"utopia-php/database": "dev-feat-framework-v2 as 0.43.99",
"utopia-php/domains": "0.3.*",
"utopia-php/dsn": "0.1.*",
"utopia-php/framework": "0.31.0",
"utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0",
"utopia-php/view": "dev-main",
"utopia-php/image": "0.5.*",
"utopia-php/locale": "0.4.*",
"utopia-php/logger": "0.3.*",
@@ -62,10 +63,9 @@
"utopia-php/platform": "0.4.*",
"utopia-php/pools": "0.4.*",
"utopia-php/preloader": "0.2.*",
"utopia-php/queue": "0.5.*",
"utopia-php/queue": "dev-feat-framework-v2 as 0.5.99",
"utopia-php/registry": "0.5.*",
"utopia-php/storage": "0.17.*",
"utopia-php/swoole": "0.5.*",
"utopia-php/storage": "dev-feat-framework-v2 as 0.17.99",
"utopia-php/vcs": "0.5.*",
"utopia-php/websocket": "0.1.*",
"resque/php-resque": "1.3.6",
@@ -83,6 +83,10 @@
{
"url": "https://github.com/appwrite/runtimes.git",
"type": "git"
},
{
"url": "https://github.com/utopia-php/view",
"type": "git"
}
],
"require-dev": {
Generated
+131 -96
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "13a3bdc7c1dec5756bf58ec73a49753d",
"content-hash": "1c2d5e7151314e8a13424d187178a92c",
"packages": [
{
"name": "adhocore/jwt",
@@ -1050,16 +1050,16 @@
},
{
"name": "matomo/device-detector",
"version": "6.1.5",
"version": "6.1.6",
"source": {
"type": "git",
"url": "https://github.com/matomo-org/device-detector.git",
"reference": "40ca2990dba2c1719e5c62168e822e0b86c167d4"
"reference": "5cbea85106e561c7138d03603eb6e05128480409"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/matomo-org/device-detector/zipball/40ca2990dba2c1719e5c62168e822e0b86c167d4",
"reference": "40ca2990dba2c1719e5c62168e822e0b86c167d4",
"url": "https://api.github.com/repos/matomo-org/device-detector/zipball/5cbea85106e561c7138d03603eb6e05128480409",
"reference": "5cbea85106e561c7138d03603eb6e05128480409",
"shasum": ""
},
"require": {
@@ -1115,7 +1115,7 @@
"source": "https://github.com/matomo-org/matomo",
"wiki": "https://dev.matomo.org/"
},
"time": "2023-08-17T16:17:41+00:00"
"time": "2023-10-02T10:01:54+00:00"
},
{
"name": "mongodb/mongodb",
@@ -2052,21 +2052,21 @@
},
{
"name": "utopia-php/cli",
"version": "0.15.0",
"version": "dev-feat-framework-v2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/cli.git",
"reference": "ccb7c8125ffe0254fef8f25744bfa376eb7bd0ea"
"reference": "18cc19b1b1d22004b924f0541f03582ca732e64e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/cli/zipball/ccb7c8125ffe0254fef8f25744bfa376eb7bd0ea",
"reference": "ccb7c8125ffe0254fef8f25744bfa376eb7bd0ea",
"url": "https://api.github.com/repos/utopia-php/cli/zipball/18cc19b1b1d22004b924f0541f03582ca732e64e",
"reference": "18cc19b1b1d22004b924f0541f03582ca732e64e",
"shasum": ""
},
"require": {
"php": ">=7.4",
"utopia-php/framework": "0.*.*"
"utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0"
},
"require-dev": {
"laravel/pint": "1.2.*",
@@ -2095,9 +2095,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/cli/issues",
"source": "https://github.com/utopia-php/cli/tree/0.15.0"
"source": "https://github.com/utopia-php/cli/tree/feat-framework-v2"
},
"time": "2023-03-01T05:55:14+00:00"
"time": "2023-10-04T12:49:42+00:00"
},
{
"name": "utopia-php/config",
@@ -2152,16 +2152,16 @@
},
{
"name": "utopia-php/database",
"version": "0.43.4",
"version": "dev-feat-framework-v2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/database.git",
"reference": "cabdd02e8dc1732eb0b22007c511e7bb3caa5c8c"
"reference": "1d4ab3dfafbe7a3adfd167e5e288c19634c223ce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/database/zipball/cabdd02e8dc1732eb0b22007c511e7bb3caa5c8c",
"reference": "cabdd02e8dc1732eb0b22007c511e7bb3caa5c8c",
"url": "https://api.github.com/repos/utopia-php/database/zipball/1d4ab3dfafbe7a3adfd167e5e288c19634c223ce",
"reference": "1d4ab3dfafbe7a3adfd167e5e288c19634c223ce",
"shasum": ""
},
"require": {
@@ -2169,7 +2169,7 @@
"ext-pdo": "*",
"php": ">=8.0",
"utopia-php/cache": "0.8.*",
"utopia-php/framework": "0.*.*",
"utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0",
"utopia-php/mongo": "0.3.*"
},
"require-dev": {
@@ -2202,9 +2202,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/database/issues",
"source": "https://github.com/utopia-php/database/tree/0.43.4"
"source": "https://github.com/utopia-php/database/tree/feat-framework-v2"
},
"time": "2023-09-28T09:00:05+00:00"
"time": "2023-10-05T09:43:50+00:00"
},
{
"name": "utopia-php/domains",
@@ -2315,31 +2315,33 @@
},
{
"name": "utopia-php/framework",
"version": "0.31.0",
"version": "dev-fix-v2-swoole-coroutines",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/framework.git",
"reference": "207f77378965fca9a9bc3783ea379d3549f86bc0"
"reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/framework/zipball/207f77378965fca9a9bc3783ea379d3549f86bc0",
"reference": "207f77378965fca9a9bc3783ea379d3549f86bc0",
"url": "https://api.github.com/repos/utopia-php/framework/zipball/e34ed9c34d50b64e997ab53fd4f486b6179ae6ef",
"reference": "e34ed9c34d50b64e997ab53fd4f486b6179ae6ef",
"shasum": ""
},
"require": {
"ext-swoole": "*",
"php": ">=8.0"
},
"require-dev": {
"laravel/pint": "^1.2",
"phpbench/phpbench": "^1.2",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.5.25"
"phpunit/phpunit": "^9.5.25",
"swoole/ide-helper": "4.8.3"
},
"type": "library",
"autoload": {
"psr-4": {
"Utopia\\": "src/"
"Utopia\\Http\\": "src/Http"
}
},
"notification-url": "https://packagist.org/downloads/",
@@ -2354,9 +2356,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/framework/issues",
"source": "https://github.com/utopia-php/framework/tree/0.31.0"
"source": "https://github.com/utopia-php/framework/tree/fix-v2-swoole-coroutines"
},
"time": "2023-08-30T16:10:04+00:00"
"time": "2023-10-04T11:53:40+00:00"
},
{
"name": "utopia-php/image",
@@ -2875,22 +2877,22 @@
},
{
"name": "utopia-php/queue",
"version": "0.5.3",
"version": "dev-feat-framework-v2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/queue.git",
"reference": "8e8b6cb27172713fe5d8b7b092ce68516caf129a"
"reference": "a6ff7bdc9f02497cce18dadb6919f65cca77f236"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/queue/zipball/8e8b6cb27172713fe5d8b7b092ce68516caf129a",
"reference": "8e8b6cb27172713fe5d8b7b092ce68516caf129a",
"url": "https://api.github.com/repos/utopia-php/queue/zipball/a6ff7bdc9f02497cce18dadb6919f65cca77f236",
"reference": "a6ff7bdc9f02497cce18dadb6919f65cca77f236",
"shasum": ""
},
"require": {
"php": ">=8.0",
"utopia-php/cli": "0.15.*",
"utopia-php/framework": "0.*.*"
"utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0"
},
"require-dev": {
"laravel/pint": "^0.2.3",
@@ -2930,9 +2932,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/queue/issues",
"source": "https://github.com/utopia-php/queue/tree/0.5.3"
"source": "https://github.com/utopia-php/queue/tree/feat-framework-v2"
},
"time": "2023-05-24T19:06:04+00:00"
"time": "2023-10-04T12:38:34+00:00"
},
{
"name": "utopia-php/registry",
@@ -2988,16 +2990,16 @@
},
{
"name": "utopia-php/storage",
"version": "0.17.0",
"version": "dev-feat-framework-v2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/storage.git",
"reference": "efec5376c02d3d8330f1beb1469e6d6e313e21ee"
"reference": "5794b3a7351ed89abab16981990e9c13b1653f33"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/storage/zipball/efec5376c02d3d8330f1beb1469e6d6e313e21ee",
"reference": "efec5376c02d3d8330f1beb1469e6d6e313e21ee",
"url": "https://api.github.com/repos/utopia-php/storage/zipball/5794b3a7351ed89abab16981990e9c13b1653f33",
"reference": "5794b3a7351ed89abab16981990e9c13b1653f33",
"shasum": ""
},
"require": {
@@ -3009,8 +3011,7 @@
"ext-zlib": "*",
"ext-zstd": "*",
"php": ">=8.0",
"utopia-php/framework": "0.*.*",
"utopia-php/system": "0.*.*"
"utopia-php/framework": "dev-fix-v2-swoole-coroutines as 0.31.0"
},
"require-dev": {
"laravel/pint": "1.2.*",
@@ -3037,60 +3038,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/storage/issues",
"source": "https://github.com/utopia-php/storage/tree/0.17.0"
"source": "https://github.com/utopia-php/storage/tree/feat-framework-v2"
},
"time": "2023-08-21T11:28:36+00:00"
},
{
"name": "utopia-php/swoole",
"version": "0.5.0",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/swoole.git",
"reference": "c2a3a4f944a2f22945af3cbcb95b13f0769628b1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/swoole/zipball/c2a3a4f944a2f22945af3cbcb95b13f0769628b1",
"reference": "c2a3a4f944a2f22945af3cbcb95b13f0769628b1",
"shasum": ""
},
"require": {
"ext-swoole": "*",
"php": ">=8.0",
"utopia-php/framework": "0.*.*"
},
"require-dev": {
"laravel/pint": "1.2.*",
"phpunit/phpunit": "^9.3",
"swoole/ide-helper": "4.8.3",
"vimeo/psalm": "4.15.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Utopia\\Swoole\\": "src/Swoole"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "An extension for Utopia Framework to work with PHP Swoole as a PHP FPM alternative",
"keywords": [
"framework",
"http",
"php",
"server",
"swoole",
"upf",
"utopia"
],
"support": {
"issues": "https://github.com/utopia-php/swoole/issues",
"source": "https://github.com/utopia-php/swoole/tree/0.5.0"
},
"time": "2022-10-19T22:19:07+00:00"
"time": "2023-10-04T11:42:54+00:00"
},
{
"name": "utopia-php/system",
@@ -3198,6 +3148,53 @@
},
"time": "2023-09-13T19:05:52+00:00"
},
{
"name": "utopia-php/view",
"version": "dev-main",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/view",
"reference": "013a495af4e625df172d9bd534011014cb32bbab"
},
"require": {
"php": ">=8.0"
},
"require-dev": {
"laravel/pint": "^1.2",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^9.5.25"
},
"default-branch": true,
"type": "library",
"autoload": {
"psr-4": {
"Utopia\\View\\": "src/View"
}
},
"scripts": {
"lint": [
"vendor/bin/pint --test"
],
"format": [
"vendor/bin/pint"
],
"check": [
"vendor/bin/phpstan analyse -c phpstan.neon"
],
"test": [
"vendor/bin/phpunit --configuration phpunit.xml"
]
},
"license": [
"MIT"
],
"description": "A simple, light and advanced PHP rendering engine",
"keywords": [
"php",
"view"
],
"time": "2023-09-10T12:07:26+00:00"
},
{
"name": "utopia-php/websocket",
"version": "0.1.0",
@@ -5993,9 +5990,47 @@
"time": "2023-08-28T11:09:02+00:00"
}
],
"aliases": [],
"aliases": [
{
"package": "utopia-php/cli",
"version": "dev-feat-framework-v2",
"alias": "0.15.99",
"alias_normalized": "0.15.99.0"
},
{
"package": "utopia-php/database",
"version": "dev-feat-framework-v2",
"alias": "0.43.99",
"alias_normalized": "0.43.99.0"
},
{
"package": "utopia-php/framework",
"version": "dev-fix-v2-swoole-coroutines",
"alias": "0.31.0",
"alias_normalized": "0.31.0.0"
},
{
"package": "utopia-php/queue",
"version": "dev-feat-framework-v2",
"alias": "0.5.99",
"alias_normalized": "0.5.99.0"
},
{
"package": "utopia-php/storage",
"version": "dev-feat-framework-v2",
"alias": "0.17.99",
"alias_normalized": "0.17.99.0"
}
],
"minimum-stability": "stable",
"stability-flags": [],
"stability-flags": {
"utopia-php/cli": 20,
"utopia-php/database": 20,
"utopia-php/framework": 20,
"utopia-php/view": 20,
"utopia-php/queue": 20,
"utopia-php/storage": 20
},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
+15 -15
View File
@@ -8,7 +8,7 @@ Setting an alias allows the route to be also accessible from the alias URL.
The first parameter specifies the alias URL, the second parameter specifies default values for route parameters.
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->alias('/v1/storage/files', ['bucketId' => 'default'])
```
@@ -17,7 +17,7 @@ App::post('/v1/storage/buckets/:bucketId/files')
Used as an abstract description of the route.
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->desc('Create File')
```
@@ -26,14 +26,14 @@ App::post('/v1/storage/buckets/:bucketId/files')
Groups array is used to group one or more routes with one or more hooks functionality.
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->groups(['api'])
```
In the above example groups() is used to define the current route as part of the routes that shares a common init middleware hook.
```php
App::init()
Http::init()
->groups(['api'])
->action(
some code.....
@@ -52,7 +52,7 @@ Appwrite uses different labels to achieve different things, for example:
- scope - Defines the route permissions scope.
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->label('scope', 'files.write')
```
@@ -66,7 +66,7 @@ App::post('/v1/storage/buckets/:bucketId/files')
- audits.resource - Signals the extraction part of the resource.
```php
App::post('/v1/account/create')
Http::post('/v1/account/create')
->label('audits.event', 'account.create')
->label('audits.resource', 'user/{response.$id}')
->label('audits.userId', '{response.$id}')
@@ -84,7 +84,7 @@ App::post('/v1/account/create')
* sdk.offline.response.key - JSON property name that has the ID. Defaults to $id
```php
App::post('/v1/account/jwt')
Http::post('/v1/account/jwt')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION])
->label('sdk.namespace', 'account')
->label('sdk.method', 'createJWT')
@@ -100,7 +100,7 @@ App::post('/v1/account/jwt')
- cache.resource - Identifies the cached resource.
```php
App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
Http::get('/v1/storage/buckets/:bucketId/files/:fileId/preview')
->label('cache', true)
->label('cache.resource', 'file/{request.fileId}')
```
@@ -115,7 +115,7 @@ When using the example below, we configure the abuse mechanism to allow this key
constructed from the combination of the ip, http method, url, userId to hit the route maximum 60 times in 1 hour (60 seconds \* 60 minutes).
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->label('abuse-key', 'ip:{ip},method:{method},url:{url},userId:{userId}')
->label('abuse-limit', 60)
->label('abuse-time', 3600)
@@ -127,7 +127,7 @@ App::post('/v1/storage/buckets/:bucketId/files')
Placeholders marked as `[]` are parsed and replaced with their real values.
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->label('event', 'buckets.[bucketId].files.[fileId].create')
```
@@ -145,7 +145,7 @@ As the name implies, `param()` is used to define a request parameter.
- An array of injections
```php
App::get('/v1/account/logs')
Http::get('/v1/account/logs')
->param('queries', [], new Queries([new Limit(), new Offset()]), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/queries). Only supported methods are limit and offset', true)
```
@@ -154,14 +154,14 @@ App::get('/v1/account/logs')
inject is used to inject dependencies pre-bounded to the app.
```php
App::post('/v1/storage/buckets/:bucketId/files')
Http::post('/v1/storage/buckets/:bucketId/files')
->inject('user')
```
In the example above, the user object is injected into the route pre-bounded using `App::setResource()`.
In the example above, the user object is injected into the route pre-bounded using `Http::setResource()`.
```php
App::setResource('user', function() {
Http::setResource('user', function() {
some code...
});
```
@@ -170,7 +170,7 @@ some code...
Action populates the actual route code and has to be very clear and understandable. A good route stays simple and doesn't contain complex logic. An action is where we describe our business needs in code, and combine different libraries to work together and tell our story.
```php
App::post('/v1/account/sessions/anonymous')
Http::post('/v1/account/sessions/anonymous')
->action(function (Request $request) {
some code...
});
+1 -1
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Auth\OAuth2;
use Appwrite\Auth\OAuth2;
use Utopia\Exception;
use Utopia\Http\Exception;
class Mock extends OAuth2
{
+1 -1
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Auth\OAuth2;
use Appwrite\Auth\OAuth2;
use Utopia\Exception;
use Utopia\Http\Exception;
class Stripe extends OAuth2
{
+1 -1
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Auth\Validator;
use Utopia\Validator;
use Utopia\Http\Validator;
/**
* Password.
+1 -1
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Auth\Validator;
use Utopia\Validator;
use Utopia\Http\Validator;
/**
* Phone.
+1 -1
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Event\Validator;
use Utopia\Config\Config;
use Utopia\Validator;
use Utopia\Http\Validator;
class Event extends Validator
{
+21 -21
View File
@@ -6,26 +6,26 @@ use Appwrite\GraphQL\Exception as GQLException;
use Appwrite\Promises\Swoole;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Exception;
use Utopia\Route;
use Utopia\Http\Http;
use Utopia\Http\Exception;
use Utopia\Http\Route;
class Resolvers
{
/**
* Create a resolver for a given API {@see Route}.
*
* @param App $utopia
* @param Http $utopia
* @param ?Route $route
* @return callable
*/
public static function api(
App $utopia,
Http $utopia,
?Route $route,
): callable {
return static fn($type, $args, $context, $info) => new Swoole(
function (callable $resolve, callable $reject) use ($utopia, $route, $args, $context, $info) {
/** @var App $utopia */
/** @var Http $utopia */
/** @var Response $response */
/** @var Request $request */
@@ -60,14 +60,14 @@ class Resolvers
/**
* Create a resolver for a document in a specified database and collection with a specific method type.
*
* @param App $utopia
* @param Http $utopia
* @param string $databaseId
* @param string $collectionId
* @param string $methodType
* @return callable
*/
public static function document(
App $utopia,
Http $utopia,
string $databaseId,
string $collectionId,
string $methodType,
@@ -82,14 +82,14 @@ class Resolvers
/**
* Create a resolver for getting a document in a specified database and collection.
*
* @param App $utopia
* @param Http $utopia
* @param string $databaseId
* @param string $collectionId
* @param callable $url
* @return callable
*/
public static function documentGet(
App $utopia,
Http $utopia,
string $databaseId,
string $collectionId,
callable $url,
@@ -111,7 +111,7 @@ class Resolvers
/**
* Create a resolver for listing documents in a specified database and collection.
*
* @param App $utopia
* @param Http $utopia
* @param string $databaseId
* @param string $collectionId
* @param callable $url
@@ -119,7 +119,7 @@ class Resolvers
* @return callable
*/
public static function documentList(
App $utopia,
Http $utopia,
string $databaseId,
string $collectionId,
callable $url,
@@ -147,7 +147,7 @@ class Resolvers
/**
* Create a resolver for creating a document in a specified database and collection.
*
* @param App $utopia
* @param Http $utopia
* @param string $databaseId
* @param string $collectionId
* @param callable $url
@@ -155,7 +155,7 @@ class Resolvers
* @return callable
*/
public static function documentCreate(
App $utopia,
Http $utopia,
string $databaseId,
string $collectionId,
callable $url,
@@ -179,7 +179,7 @@ class Resolvers
/**
* Create a resolver for updating a document in a specified database and collection.
*
* @param App $utopia
* @param Http $utopia
* @param string $databaseId
* @param string $collectionId
* @param callable $url
@@ -187,7 +187,7 @@ class Resolvers
* @return callable
*/
public static function documentUpdate(
App $utopia,
Http $utopia,
string $databaseId,
string $collectionId,
callable $url,
@@ -211,14 +211,14 @@ class Resolvers
/**
* Create a resolver for deleting a document in a specified database and collection.
*
* @param App $utopia
* @param Http $utopia
* @param string $databaseId
* @param string $collectionId
* @param callable $url
* @return callable
*/
public static function documentDelete(
App $utopia,
Http $utopia,
string $databaseId,
string $collectionId,
callable $url,
@@ -238,7 +238,7 @@ class Resolvers
}
/**
* @param App $utopia
* @param Http $utopia
* @param Request $request
* @param Response $response
* @param callable $resolve
@@ -249,7 +249,7 @@ class Resolvers
* @throws Exception
*/
private static function resolve(
App $utopia,
Http $utopia,
Request $request,
Response $response,
callable $resolve,
@@ -302,7 +302,7 @@ class Resolvers
private static function escapePayload(array $payload, int $depth)
{
if ($depth > App::getEnv('_APP_GRAPHQL_MAX_DEPTH', 3)) {
if ($depth > Http::getEnv('_APP_GRAPHQL_MAX_DEPTH', 3)) {
return;
}
+10 -10
View File
@@ -6,9 +6,9 @@ use Appwrite\GraphQL\Types\Mapper;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema as GQLSchema;
use Utopia\App;
use Utopia\Exception;
use Utopia\Route;
use Utopia\Http\Http;
use Utopia\Http\Exception;
use Utopia\Http\Route;
class Schema
{
@@ -17,7 +17,7 @@ class Schema
/**
*
* @param App $utopia
* @param Http $utopia
* @param callable $complexity Function to calculate complexity
* @param callable $attributes Function to get attributes
* @param array $urls Array of functions to get urls for specific method types
@@ -26,13 +26,13 @@ class Schema
* @throws Exception
*/
public static function build(
App $utopia,
Http $utopia,
callable $complexity,
callable $attributes,
array $urls,
array $params,
): GQLSchema {
App::setResource('utopia:graphql', static function () use ($utopia) {
Http::setResource('utopia:graphql', static function () use ($utopia) {
return $utopia;
});
@@ -80,12 +80,12 @@ class Schema
* This function iterates all API routes and builds a GraphQL
* schema defining types and resolvers for all response models.
*
* @param App $utopia
* @param Http $utopia
* @param callable $complexity
* @return array
* @throws Exception
*/
protected static function api(App $utopia, callable $complexity): array
protected static function api(Http $utopia, callable $complexity): array
{
Mapper::init($utopia
->getResource('response')
@@ -134,7 +134,7 @@ class Schema
* Iterates all of a projects attributes and builds GraphQL
* queries and mutations for the collections they make up.
*
* @param App $utopia
* @param Http $utopia
* @param callable $complexity
* @param callable $attributes
* @param array $urls
@@ -143,7 +143,7 @@ class Schema
* @throws \Exception
*/
protected static function collections(
App $utopia,
Http $utopia,
callable $complexity,
callable $attributes,
array $urls,
+23 -23
View File
@@ -8,10 +8,10 @@ use Exception;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\UnionType;
use Utopia\App;
use Utopia\Route;
use Utopia\Validator;
use Utopia\Validator\Nullable;
use Utopia\Http\Http;
use Utopia\Http\Route;
use Utopia\Http\Validator;
use Utopia\Http\Validator\Nullable;
class Mapper
{
@@ -75,7 +75,7 @@ class Mapper
}
public static function route(
App $utopia,
Http $utopia,
Route $route,
callable $complexity
): iterable {
@@ -205,7 +205,7 @@ class Mapper
/**
* Map a {@see Route} parameter to a GraphQL Type
*
* @param App $utopia
* @param Http $utopia
* @param Validator|callable $validator
* @param bool $required
* @param array $injections
@@ -213,7 +213,7 @@ class Mapper
* @throws Exception
*/
public static function param(
App $utopia,
Http $utopia,
Validator|callable $validator,
bool $required,
array $injections
@@ -232,20 +232,20 @@ class Mapper
case 'Appwrite\Network\Validator\CNAME':
case 'Appwrite\Task\Validator\Cron':
case 'Appwrite\Utopia\Database\Validator\CustomId':
case 'Utopia\Validator\Domain':
case 'Utopia\Http\Validator\Domain':
case 'Appwrite\Network\Validator\Email':
case 'Appwrite\Event\Validator\Event':
case 'Appwrite\Event\Validator\FunctionEvent':
case 'Utopia\Validator\HexColor':
case 'Utopia\Validator\Host':
case 'Utopia\Validator\IP':
case 'Utopia\Http\Validator\HexColor':
case 'Utopia\Http\Validator\Host':
case 'Utopia\Http\Validator\IP':
case 'Utopia\Database\Validator\Key':
case 'Utopia\Validator\Origin':
case 'Utopia\Http\Validator\Origin':
case 'Appwrite\Auth\Validator\Password':
case 'Utopia\Validator\Text':
case 'Utopia\Http\Validator\Text':
case 'Utopia\Database\Validator\UID':
case 'Utopia\Validator\URL':
case 'Utopia\Validator\WhiteList':
case 'Utopia\Http\Validator\URL':
case 'Utopia\Http\Validator\WhiteList':
default:
$type = Type::string();
break;
@@ -273,10 +273,10 @@ class Mapper
case 'Appwrite\Utopia\Database\Validator\Queries\Variables':
$type = Type::listOf(Type::string());
break;
case 'Utopia\Validator\Boolean':
case 'Utopia\Http\Validator\Boolean':
$type = Type::boolean();
break;
case 'Utopia\Validator\ArrayList':
case 'Utopia\Http\Validator\ArrayList':
$type = Type::listOf(self::param(
$utopia,
$validator->getValidator(),
@@ -284,18 +284,18 @@ class Mapper
$injections
));
break;
case 'Utopia\Validator\Integer':
case 'Utopia\Validator\Numeric':
case 'Utopia\Validator\Range':
case 'Utopia\Http\Validator\Integer':
case 'Utopia\Http\Validator\Numeric':
case 'Utopia\Http\Validator\Range':
$type = Type::int();
break;
case 'Utopia\Validator\FloatValidator':
case 'Utopia\Http\Validator\FloatValidator':
$type = Type::float();
break;
case 'Utopia\Validator\Assoc':
case 'Utopia\Http\Validator\Assoc':
$type = Types::assoc();
break;
case 'Utopia\Validator\JSON':
case 'Utopia\Http\Validator\JSON':
$type = Types::json();
break;
case 'Utopia\Storage\Validator\File':
+2 -2
View File
@@ -5,7 +5,7 @@ namespace Appwrite\Messaging\Adapter;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Appwrite\Messaging\Adapter;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Role;
@@ -140,7 +140,7 @@ class Realtime extends Adapter
$userId = array_key_exists('userId', $options) ? $options['userId'] : null;
$redis = new \Redis(); //TODO: make this part of the constructor
$redis->connect(App::getEnv('_APP_REDIS_HOST', ''), App::getEnv('_APP_REDIS_PORT', ''));
$redis->connect(Http::getEnv('_APP_REDIS_HOST', ''), Http::getEnv('_APP_REDIS_PORT', ''));
$redis->publish('realtime', json_encode([
'project' => $projectId,
'roles' => $roles,
+2 -2
View File
@@ -9,7 +9,7 @@ use Utopia\Database\Query;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Exception;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Validator\Authorization;
@@ -231,7 +231,7 @@ abstract class Migration
default => 'projects',
};
if (!$this->projectDB->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), $name)) {
if (!$this->projectDB->exists(Http::getEnv('_APP_DB_SCHEMA', 'appwrite'), $name)) {
$attributes = [];
$indexes = [];
$collection = $this->collections[$collectionType][$id];
+2 -2
View File
@@ -6,7 +6,7 @@ use Appwrite\Migration\Migration;
use Appwrite\OpenSSL\OpenSSL;
use Exception;
use PDO;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Database;
@@ -1486,7 +1486,7 @@ class V15 extends Migration
*/
protected function encryptFilter(string $value): string
{
$key = App::getEnv('_APP_OPENSSL_KEY_V1');
$key = Http::getEnv('_APP_OPENSSL_KEY_V1');
$iv = OpenSSL::randomPseudoBytes(OpenSSL::cipherIVLength(OpenSSL::CIPHER_AES_128_GCM));
$tag = null;
+2 -2
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Migration\Version;
use Appwrite\Migration\Migration;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Database;
@@ -709,7 +709,7 @@ class V19 extends Migration
if (empty($document->getAttribute('scheduleId', null))) {
$schedule = $this->consoleDB->createDocument('schedules', new Document([
'region' => App::getEnv('_APP_REGION', 'default'), // Todo replace with projects region
'region' => Http::getEnv('_APP_REGION', 'default'), // Todo replace with projects region
'resourceType' => 'function',
'resourceId' => $document->getId(),
'resourceInternalId' => $document->getInternalId(),
+1 -1
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Network\Validator;
use Utopia\Validator;
use Utopia\Http\Validator;
class CNAME extends Validator
{
+2 -2
View File
@@ -2,14 +2,14 @@
namespace Appwrite\Network\Validator;
use Utopia\Validator;
use Utopia\Http\Validator;
/**
* Email
*
* Validate that an variable is a valid email address
*
* @package Utopia\Validator
* @package Utopia\Http\Validator
*/
class Email extends Validator
{
+2 -2
View File
@@ -2,8 +2,8 @@
namespace Appwrite\Network\Validator;
use Utopia\Validator\Hostname;
use Utopia\Validator;
use Utopia\Http\Validator\Hostname;
use Utopia\Http\Validator;
class Origin extends Validator
{
@@ -4,7 +4,7 @@ namespace Appwrite\Platform\Tasks;
use Exception;
use League\Csv\CannotInsertRecord;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Action;
use Utopia\Cache\Cache;
@@ -73,7 +73,7 @@ class CalcTierStats extends Action
}
/**
* @throws \Utopia\Exception
* @throws \Utopia\Http\Exception
* @throws CannotInsertRecord
*/
public function action(Group $pools, Cache $cache, Database $dbForConsole, Registry $register): void
@@ -84,7 +84,7 @@ class CalcTierStats extends Action
Console::success(APP_NAME . ' cloud free tier stats calculation has started');
/* Initialise new Utopia app */
$app = new App('UTC');
$app = new Http('UTC');
$console = $app->getResource('console');
/** CSV stuff */
@@ -329,8 +329,8 @@ class CalcTierStats extends Action
try {
/** Addresses */
$mail->setFrom(App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), 'Appwrite Cloud Hamster');
$recipients = explode(',', App::getEnv('_APP_USERS_STATS_RECIPIENTS', ''));
$mail->setFrom(Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), 'Appwrite Cloud Hamster');
$recipients = explode(',', Http::getEnv('_APP_USERS_STATS_RECIPIENTS', ''));
foreach ($recipients as $recipient) {
$mail->addAddress($recipient);
@@ -3,7 +3,7 @@
namespace Appwrite\Platform\Tasks;
use Exception;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Platform\Action;
use Utopia\Cache\Cache;
use Utopia\CLI\Console;
@@ -55,7 +55,7 @@ class CalcUsersStats extends Action
Console::success(APP_NAME . ' cloud Users calculation has started');
/* Initialise new Utopia app */
$app = new App('UTC');
$app = new Http('UTC');
$console = $app->getResource('console');
/** CSV stuff */
@@ -154,8 +154,8 @@ class CalcUsersStats extends Action
try {
/** Addresses */
$mail->setFrom(App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), 'Appwrite Cloud Hamster');
$recipients = explode(',', App::getEnv('_APP_USERS_STATS_RECIPIENTS', ''));
$mail->setFrom(Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), 'Appwrite Cloud Hamster');
$recipients = explode(',', Http::getEnv('_APP_USERS_STATS_RECIPIENTS', ''));
foreach ($recipients as $recipient) {
$mail->addAddress($recipient);
+20 -20
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Platform\Tasks;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Appwrite\ClamAV\Network;
use Utopia\Logger\Logger;
@@ -35,11 +35,11 @@ class Doctor extends Action
/ \ ) __/ ) __/\ /\ / ) / )( )( ) _) _ )(( O )
\_/\_/(__) (__) (_/\_)(__\_)(__) (__) (____)(_)(__)\__/ ");
Console::log("\n" . '👩‍⚕️ Running ' . APP_NAME . ' Doctor for version ' . App::getEnv('_APP_VERSION', 'UNKNOWN') . ' ...' . "\n");
Console::log("\n" . '👩‍⚕️ Running ' . APP_NAME . ' Doctor for version ' . Http::getEnv('_APP_VERSION', 'UNKNOWN') . ' ...' . "\n");
Console::log('[Settings]');
$domain = new Domain(App::getEnv('_APP_DOMAIN'));
$domain = new Domain(Http::getEnv('_APP_DOMAIN'));
if (!$domain->isKnown() || $domain->isTest()) {
Console::log('🔴 Hostname has no public suffix (' . $domain->get() . ')');
@@ -47,7 +47,7 @@ class Doctor extends Action
Console::log('🟢 Hostname has a public suffix (' . $domain->get() . ')');
}
$domain = new Domain(App::getEnv('_APP_DOMAIN_TARGET'));
$domain = new Domain(Http::getEnv('_APP_DOMAIN_TARGET'));
if (!$domain->isKnown() || $domain->isTest()) {
Console::log('🔴 CNAME target has no public suffix (' . $domain->get() . ')');
@@ -55,27 +55,27 @@ class Doctor extends Action
Console::log('🟢 CNAME target has a public suffix (' . $domain->get() . ')');
}
if (App::getEnv('_APP_OPENSSL_KEY_V1') === 'your-secret-key' || empty(App::getEnv('_APP_OPENSSL_KEY_V1'))) {
if (Http::getEnv('_APP_OPENSSL_KEY_V1') === 'your-secret-key' || empty(Http::getEnv('_APP_OPENSSL_KEY_V1'))) {
Console::log('🔴 Not using a unique secret key for encryption');
} else {
Console::log('🟢 Using a unique secret key for encryption');
}
if (App::getEnv('_APP_ENV', 'development') !== 'production') {
if (Http::getEnv('_APP_ENV', 'development') !== 'production') {
Console::log('🔴 App environment is set for development');
} else {
Console::log('🟢 App environment is set for production');
}
if ('enabled' !== App::getEnv('_APP_OPTIONS_ABUSE', 'disabled')) {
if ('enabled' !== Http::getEnv('_APP_OPTIONS_ABUSE', 'disabled')) {
Console::log('🔴 Abuse protection is disabled');
} else {
Console::log('🟢 Abuse protection is enabled');
}
$authWhitelistRoot = App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', null);
$authWhitelistEmails = App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null);
$authWhitelistIPs = App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null);
$authWhitelistRoot = Http::getEnv('_APP_CONSOLE_WHITELIST_ROOT', null);
$authWhitelistEmails = Http::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null);
$authWhitelistIPs = Http::getEnv('_APP_CONSOLE_WHITELIST_IPS', null);
if (
empty($authWhitelistRoot)
@@ -87,20 +87,20 @@ class Doctor extends Action
Console::log('🟢 Console access limits are enabled');
}
if ('enabled' !== App::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled')) {
if ('enabled' !== Http::getEnv('_APP_OPTIONS_FORCE_HTTPS', 'disabled')) {
Console::log('🔴 HTTPS force option is disabled');
} else {
Console::log('🟢 HTTPS force option is enabled');
}
if ('enabled' !== App::getEnv('_APP_OPTIONS_FUNCTIONS_FORCE_HTTPS', 'disabled')) {
if ('enabled' !== Http::getEnv('_APP_OPTIONS_FUNCTIONS_FORCE_HTTPS', 'disabled')) {
Console::log('🔴 HTTPS force option is disabled for function domains');
} else {
Console::log('🟢 HTTPS force option is enabled for function domains');
}
$providerName = App::getEnv('_APP_LOGGING_PROVIDER', '');
$providerConfig = App::getEnv('_APP_LOGGING_CONFIG', '');
$providerName = Http::getEnv('_APP_LOGGING_PROVIDER', '');
$providerConfig = Http::getEnv('_APP_LOGGING_CONFIG', '');
if (empty($providerName) || empty($providerConfig) || !Logger::hasProvider($providerName)) {
Console::log('🔴 Logging adapter is disabled');
@@ -162,11 +162,11 @@ class Doctor extends Action
}
}
if (App::getEnv('_APP_STORAGE_ANTIVIRUS') === 'enabled') { // Check if scans are enabled
if (Http::getEnv('_APP_STORAGE_ANTIVIRUS') === 'enabled') { // Check if scans are enabled
try {
$antivirus = new Network(
App::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),
(int) App::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)
Http::getEnv('_APP_STORAGE_ANTIVIRUS_HOST', 'clamav'),
(int) Http::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310)
);
if ((@$antivirus->ping())) {
@@ -249,12 +249,12 @@ class Doctor extends Action
}
try {
if (App::isProduction()) {
if (Http::isProduction()) {
Console::log('');
$version = \json_decode(@\file_get_contents(App::getEnv('_APP_HOME', 'http://localhost') . '/version'), true);
$version = \json_decode(@\file_get_contents(Http::getEnv('_APP_HOME', 'http://localhost') . '/version'), true);
if ($version && isset($version['version'])) {
if (\version_compare($version['version'], App::getEnv('_APP_VERSION', 'UNKNOWN')) === 0) {
if (\version_compare($version['version'], Http::getEnv('_APP_VERSION', 'UNKNOWN')) === 0) {
Console::info('You are running the latest version of ' . APP_NAME . '! 🥳');
} else {
Console::info('A new version (' . $version['version'] . ') is available! 🥳' . "\n");
+5 -5
View File
@@ -4,7 +4,7 @@ namespace Appwrite\Platform\Tasks;
use Appwrite\Network\Validator\Origin;
use Exception;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Platform\Action;
use Utopia\Cache\Cache;
use Utopia\CLI\Console;
@@ -48,7 +48,7 @@ class Hamster extends Action
public function __construct()
{
$this->mixpanel = new Mixpanel(App::getEnv('_APP_MIXPANEL_TOKEN', ''));
$this->mixpanel = new Mixpanel(Http::getEnv('_APP_MIXPANEL_TOKEN', ''));
$this
->desc('Get stats for projects')
@@ -261,9 +261,9 @@ class Hamster extends Action
Console::title('Cloud Hamster V1');
Console::success(APP_NAME . ' cloud hamster process has started');
$sleep = (int) App::getEnv('_APP_HAMSTER_INTERVAL', '30'); // 30 seconds (by default)
$sleep = (int) Http::getEnv('_APP_HAMSTER_INTERVAL', '30'); // 30 seconds (by default)
$jobInitTime = App::getEnv('_APP_HAMSTER_TIME', '22:00'); // (hour:minutes)
$jobInitTime = Http::getEnv('_APP_HAMSTER_TIME', '22:00'); // (hour:minutes)
$now = new \DateTime();
$now->setTimezone(new \DateTimeZone(date_default_timezone_get()));
$next = new \DateTime($now->format("Y-m-d $jobInitTime"));
@@ -286,7 +286,7 @@ class Hamster extends Action
$loopStart = microtime(true);
/* Initialise new Utopia app */
$app = new App('UTC');
$app = new Http('UTC');
Console::info('Getting stats for all projects');
$this->getStatsPerProject($pools, $cache, $dbForConsole);
+1 -1
View File
@@ -11,7 +11,7 @@ use Utopia\Analytics\Adapter\GoogleAnalytics;
use Utopia\Analytics\Event;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Text;
use Utopia\Platform\Action;
class Install extends Action
+8 -8
View File
@@ -4,7 +4,7 @@ namespace Appwrite\Platform\Tasks;
use Appwrite\Event\Certificate;
use Appwrite\Event\Delete;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Database;
use Utopia\Database\Document;
@@ -123,14 +123,14 @@ class Maintenance extends Action
}
// # of days in seconds (1 day = 86400s)
$interval = (int) App::getEnv('_APP_MAINTENANCE_INTERVAL', '86400');
$executionLogsRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_EXECUTION', '1209600');
$auditLogRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_AUDIT', '1209600');
$abuseLogsRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_ABUSE', '86400');
$usageStatsRetentionHourly = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_USAGE_HOURLY', '8640000'); //100 days
$interval = (int) Http::getEnv('_APP_MAINTENANCE_INTERVAL', '86400');
$executionLogsRetention = (int) Http::getEnv('_APP_MAINTENANCE_RETENTION_EXECUTION', '1209600');
$auditLogRetention = (int) Http::getEnv('_APP_MAINTENANCE_RETENTION_AUDIT', '1209600');
$abuseLogsRetention = (int) Http::getEnv('_APP_MAINTENANCE_RETENTION_ABUSE', '86400');
$usageStatsRetentionHourly = (int) Http::getEnv('_APP_MAINTENANCE_RETENTION_USAGE_HOURLY', '8640000'); //100 days
$cacheRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_CACHE', '2592000'); // 30 days
$schedulesDeletionRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_SCHEDULES', '86400'); // 1 Day
$cacheRetention = (int) Http::getEnv('_APP_MAINTENANCE_RETENTION_CACHE', '2592000'); // 30 days
$schedulesDeletionRetention = (int) Http::getEnv('_APP_MAINTENANCE_RETENTION_SCHEDULES', '86400'); // 1 Day
Console::loop(function () use ($interval, $executionLogsRetention, $abuseLogsRetention, $auditLogRetention, $cacheRetention, $schedulesDeletionRetention, $usageStatsRetentionHourly, $dbForConsole) {
$time = DateTime::now();
+3 -3
View File
@@ -5,13 +5,13 @@ namespace Appwrite\Platform\Tasks;
use Utopia\Platform\Action;
use Utopia\CLI\Console;
use Appwrite\Migration\Migration;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Cache\Cache;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Text;
class Migrate extends Action
{
@@ -50,7 +50,7 @@ class Migrate extends Action
return;
}
$app = new App('UTC');
$app = new Http('UTC');
Console::success('Starting Data Migration to version ' . $version);
@@ -2,14 +2,14 @@
namespace Appwrite\Platform\Tasks;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Platform\Action;
use Utopia\Cache\Cache;
use Utopia\CLI\Console;
use Utopia\Database\Database;
use Utopia\Database\Query;
use Utopia\Pools\Group;
use Utopia\Validator\Numeric;
use Utopia\Http\Validator\Numeric;
class PatchDeleteProjectCollections extends Action
{
@@ -51,7 +51,7 @@ class PatchDeleteProjectCollections extends Action
Console::success(APP_NAME . ' delete project collections has started');
/* Initialise new Utopia app */
$app = new App('UTC');
$app = new Http('UTC');
$console = $app->getResource('console');
/** Database connections */
@@ -83,14 +83,14 @@ class PatchDeleteProjectCollections extends Action
->getResource();
$dbForProject = new Database($adapter, $cache);
$dbForProject->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite'));
$dbForProject->setDefaultDatabase(Http::getEnv('_APP_DB_SCHEMA', 'appwrite'));
$dbForProject->setNamespace('_' . $project->getInternalId());
foreach ($this->names as $name) {
if (empty($name)) {
continue;
}
if ($dbForProject->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), $name)) {
if ($dbForProject->exists(Http::getEnv('_APP_DB_SCHEMA', 'appwrite'), $name)) {
if ($dbForProject->deleteCollection($name)) {
Console::log('Deleted ' . $name);
} else {
+3 -3
View File
@@ -4,10 +4,10 @@ namespace Appwrite\Platform\Tasks;
use Utopia\Platform\Action;
use Appwrite\Event\Certificate;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Document;
use Utopia\Validator\Hostname;
use Utopia\Http\Validator\Hostname;
class SSL extends Action
{
@@ -20,7 +20,7 @@ class SSL extends Action
{
$this
->desc('Validate server certificates')
->param('domain', App::getEnv('_APP_DOMAIN', ''), new Hostname(), 'Domain to generate certificate for. If empty, main domain will be used.', true)
->param('domain', Http::getEnv('_APP_DOMAIN', ''), new Hostname(), 'Domain to generate certificate for. If empty, main domain will be used.', true)
->callback(fn ($domain) => $this->action($domain));
}
+3 -3
View File
@@ -4,7 +4,7 @@ namespace Appwrite\Platform\Tasks;
use Cron\CronExpression;
use Swoole\Timer;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Platform\Action;
use Utopia\CLI\Console;
use Utopia\Database\DateTime;
@@ -81,7 +81,7 @@ class Schedule extends Action
$paginationQueries[] = Query::cursorAfter($latestDocument);
}
$results = $dbForConsole->find('schedules', \array_merge($paginationQueries, [
Query::equal('region', [App::getEnv('_APP_REGION', 'default')]),
Query::equal('region', [Http::getEnv('_APP_REGION', 'default')]),
Query::equal('resourceType', ['function']),
Query::equal('active', [true]),
]));
@@ -128,7 +128,7 @@ class Schedule extends Action
$paginationQueries[] = Query::cursorAfter($latestDocument);
}
$results = $dbForConsole->find('schedules', \array_merge($paginationQueries, [
Query::equal('region', [App::getEnv('_APP_REGION', 'default')]),
Query::equal('region', [Http::getEnv('_APP_REGION', 'default')]),
Query::equal('resourceType', ['function']),
Query::greaterThanEqual('resourceUpdatedAt', $lastSyncUpdate),
]));
+12 -12
View File
@@ -3,14 +3,14 @@
namespace Appwrite\Platform\Tasks;
use Utopia\Platform\Action;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Text;
use Appwrite\Specification\Format\OpenAPI3;
use Appwrite\Specification\Format\Swagger2;
use Appwrite\Specification\Specification;
use Appwrite\Utopia\Response;
use Exception;
use Swoole\Http\Response as HttpResponse;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Cache\Adapter\None;
use Utopia\Cache\Cache;
use Utopia\CLI\Console;
@@ -19,7 +19,7 @@ use Utopia\Database\Adapter\MySQL;
use Utopia\Database\Database;
use Utopia\Registry\Registry;
use Utopia\Request;
use Utopia\Validator\WhiteList;
use Utopia\Http\Validator\WhiteList;
class Specs extends Action
{
@@ -40,15 +40,15 @@ class Specs extends Action
public function action(string $version, string $mode, Registry $register): void
{
$appRoutes = App::getRoutes();
$appRoutes = Http::getRoutes();
$response = new Response(new HttpResponse());
$mocks = ($mode === 'mocks');
// Mock dependencies
App::setResource('request', fn () => new Request());
App::setResource('response', fn () => $response);
App::setResource('dbForConsole', fn () => new Database(new MySQL(''), new Cache(new None())));
App::setResource('dbForProject', fn () => new Database(new MySQL(''), new Cache(new None())));
Http::setResource('request', fn () => new Request());
Http::setResource('response', fn () => $response);
Http::setResource('dbForConsole', fn () => new Database(new MySQL(''), new Cache(new None())));
Http::setResource('dbForProject', fn () => new Database(new MySQL(''), new Cache(new None())));
$platforms = [
'client' => APP_PLATFORM_CLIENT,
@@ -150,7 +150,7 @@ class Specs extends Action
foreach ($appRoutes as $key => $method) {
foreach ($method as $route) {
/** @var \Utopia\Route $route */
/** @var \Utopia\Http\Route $route */
$routeSecurity = $route->getLabel('sdk.auth', []);
$sdkPlaforms = [];
@@ -224,7 +224,7 @@ class Specs extends Action
}
}
$arguments = [new App('UTC'), $services, $routes, $models, $keys[$platform], $authCounts[$platform] ?? 0];
$arguments = [new Http('UTC'), $services, $routes, $models, $keys[$platform], $authCounts[$platform] ?? 0];
foreach (['swagger2', 'open-api3'] as $format) {
$formatInstance = match ($format) {
'swagger2' => new Swagger2(...$arguments),
@@ -233,8 +233,8 @@ class Specs extends Action
};
$specs = new Specification($formatInstance);
$endpoint = App::getEnv('_APP_HOME', '[HOSTNAME]');
$email = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$endpoint = Http::getEnv('_APP_HOME', '[HOSTNAME]');
$email = Http::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM);
$formatInstance
->setParam('name', APP_NAME)
+1 -1
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Platform\Tasks;
use Utopia\CLI\Console;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Text;
class Upgrade extends Install
{
+3 -3
View File
@@ -4,7 +4,7 @@ namespace Appwrite\Platform\Tasks;
use Appwrite\Usage\Calculators\TimeSeries;
use InfluxDB\Database as InfluxDatabase;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Database\Database as UtopiaDatabase;
use Throwable;
@@ -41,8 +41,8 @@ class Usage extends Action
$errorLogger = fn(Throwable $error, string $action = 'syncUsageStats') => $logError($error, "usage", $action);
$interval = (int) App::getEnv('_APP_USAGE_AGGREGATION_INTERVAL', '30'); // 30 seconds (by default)
$region = App::getEnv('region', 'default');
$interval = (int) Http::getEnv('_APP_USAGE_AGGREGATION_INTERVAL', '30'); // 30 seconds (by default)
$region = Http::getEnv('region', 'default');
$usage = new TimeSeries($region, $dbForConsole, $influxDB, $getProjectDB, $register, $errorLogger);
Console::loop(function () use ($interval, $usage) {
+2 -2
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Platform\Tasks;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Config\Config;
use Utopia\CLI\Console;
use Utopia\Platform\Action;
@@ -33,7 +33,7 @@ class Vars extends Action
}
foreach ($vars as $key => $value) {
Console::log('- ' . $value['name'] . '=' . App::getEnv($value['name'], ''));
Console::log('- ' . $value['name'] . '=' . Http::getEnv($value['name'], ''));
}
}
}
+2 -2
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Platform\Tasks;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\CLI\Console;
use Utopia\Platform\Action;
@@ -18,7 +18,7 @@ class Version extends Action
$this
->desc('Get the server version')
->callback(function () {
Console::log(App::getEnv('_APP_VERSION', 'UNKNOWN'));
Console::log(Http::getEnv('_APP_VERSION', 'UNKNOWN'));
});
}
}
+2 -2
View File
@@ -5,8 +5,8 @@ namespace Appwrite\Platform\Tasks;
use Utopia\CLI\Console;
use Utopia\Database\DateTime;
use Utopia\Platform\Action;
use Utopia\Validator\Integer;
use Utopia\Validator\Text;
use Utopia\Http\Validator\Integer;
use Utopia\Http\Validator\Text;
class VolumeSync extends Action
{
+23 -23
View File
@@ -4,7 +4,7 @@ namespace Appwrite\Resque;
use Appwrite\Event\Usage;
use Exception;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Cache\Cache;
use Utopia\Config\Config;
use Utopia\Cache\Adapter\Sharding;
@@ -327,7 +327,7 @@ abstract class Worker
*/
public function getDevice(string $root): Device
{
$connection = App::getEnv('_APP_CONNECTIONS_STORAGE', '');
$connection = Http::getEnv('_APP_CONNECTIONS_STORAGE', '');
if (!empty($connection)) {
$acl = 'private';
@@ -364,43 +364,43 @@ abstract class Worker
return new Local($root);
}
} else {
switch (strtolower(App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL) ?? '')) {
switch (strtolower(Http::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL) ?? '')) {
case Storage::DEVICE_LOCAL:
default:
return new Local($root);
case Storage::DEVICE_S3:
$s3AccessKey = App::getEnv('_APP_STORAGE_S3_ACCESS_KEY', '');
$s3SecretKey = App::getEnv('_APP_STORAGE_S3_SECRET', '');
$s3Region = App::getEnv('_APP_STORAGE_S3_REGION', '');
$s3Bucket = App::getEnv('_APP_STORAGE_S3_BUCKET', '');
$s3AccessKey = Http::getEnv('_APP_STORAGE_S3_ACCESS_KEY', '');
$s3SecretKey = Http::getEnv('_APP_STORAGE_S3_SECRET', '');
$s3Region = Http::getEnv('_APP_STORAGE_S3_REGION', '');
$s3Bucket = Http::getEnv('_APP_STORAGE_S3_BUCKET', '');
$s3Acl = 'private';
return new S3($root, $s3AccessKey, $s3SecretKey, $s3Bucket, $s3Region, $s3Acl);
case Storage::DEVICE_DO_SPACES:
$doSpacesAccessKey = App::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', '');
$doSpacesSecretKey = App::getEnv('_APP_STORAGE_DO_SPACES_SECRET', '');
$doSpacesRegion = App::getEnv('_APP_STORAGE_DO_SPACES_REGION', '');
$doSpacesBucket = App::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', '');
$doSpacesAccessKey = Http::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', '');
$doSpacesSecretKey = Http::getEnv('_APP_STORAGE_DO_SPACES_SECRET', '');
$doSpacesRegion = Http::getEnv('_APP_STORAGE_DO_SPACES_REGION', '');
$doSpacesBucket = Http::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', '');
$doSpacesAcl = 'private';
return new DOSpaces($root, $doSpacesAccessKey, $doSpacesSecretKey, $doSpacesBucket, $doSpacesRegion, $doSpacesAcl);
case Storage::DEVICE_BACKBLAZE:
$backblazeAccessKey = App::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', '');
$backblazeSecretKey = App::getEnv('_APP_STORAGE_BACKBLAZE_SECRET', '');
$backblazeRegion = App::getEnv('_APP_STORAGE_BACKBLAZE_REGION', '');
$backblazeBucket = App::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', '');
$backblazeAccessKey = Http::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', '');
$backblazeSecretKey = Http::getEnv('_APP_STORAGE_BACKBLAZE_SECRET', '');
$backblazeRegion = Http::getEnv('_APP_STORAGE_BACKBLAZE_REGION', '');
$backblazeBucket = Http::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', '');
$backblazeAcl = 'private';
return new Backblaze($root, $backblazeAccessKey, $backblazeSecretKey, $backblazeBucket, $backblazeRegion, $backblazeAcl);
case Storage::DEVICE_LINODE:
$linodeAccessKey = App::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', '');
$linodeSecretKey = App::getEnv('_APP_STORAGE_LINODE_SECRET', '');
$linodeRegion = App::getEnv('_APP_STORAGE_LINODE_REGION', '');
$linodeBucket = App::getEnv('_APP_STORAGE_LINODE_BUCKET', '');
$linodeAccessKey = Http::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', '');
$linodeSecretKey = Http::getEnv('_APP_STORAGE_LINODE_SECRET', '');
$linodeRegion = Http::getEnv('_APP_STORAGE_LINODE_REGION', '');
$linodeBucket = Http::getEnv('_APP_STORAGE_LINODE_BUCKET', '');
$linodeAcl = 'private';
return new Linode($root, $linodeAccessKey, $linodeSecretKey, $linodeBucket, $linodeRegion, $linodeAcl);
case Storage::DEVICE_WASABI:
$wasabiAccessKey = App::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', '');
$wasabiSecretKey = App::getEnv('_APP_STORAGE_WASABI_SECRET', '');
$wasabiRegion = App::getEnv('_APP_STORAGE_WASABI_REGION', '');
$wasabiBucket = App::getEnv('_APP_STORAGE_WASABI_BUCKET', '');
$wasabiAccessKey = Http::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', '');
$wasabiSecretKey = Http::getEnv('_APP_STORAGE_WASABI_SECRET', '');
$wasabiRegion = Http::getEnv('_APP_STORAGE_WASABI_REGION', '');
$wasabiBucket = Http::getEnv('_APP_STORAGE_WASABI_BUCKET', '');
$wasabiAcl = 'private';
return new Wasabi($root, $wasabiAccessKey, $wasabiSecretKey, $wasabiBucket, $wasabiRegion, $wasabiAcl);
}
+6 -6
View File
@@ -2,14 +2,14 @@
namespace Appwrite\Specification;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Config\Config;
use Utopia\Route;
use Utopia\Http\Route;
use Appwrite\Utopia\Response\Model;
abstract class Format
{
protected App $app;
protected Http $http;
/**
* @var Route[]
@@ -50,9 +50,9 @@ abstract class Format
]
];
public function __construct(App $app, array $services, array $routes, array $models, array $keys, int $authCount)
public function __construct(Http $http, array $services, array $routes, array $models, array $keys, int $authCount)
{
$this->app = $app;
$this->http = $http;
$this->services = $services;
$this->routes = $routes;
$this->models = $models;
@@ -72,7 +72,7 @@ abstract class Format
/**
* Parse
*
* Parses Appwrite App to given format
* Parses Appwrite Http to given format
*
* @return array
*/
+20 -20
View File
@@ -7,8 +7,8 @@ use Appwrite\Template\Template;
use Appwrite\Utopia\Response\Model;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Validator;
use Utopia\Validator\Nullable;
use Utopia\Http\Validator;
use Utopia\Http\Validator\Nullable;
class OpenAPI3 extends Format
{
@@ -269,9 +269,9 @@ class OpenAPI3 extends Format
foreach ($route->getParams() as $name => $param) { // Set params
/**
* @var \Utopia\Validator $validator
* @var \Utopia\Http\Validator $validator
*/
$validator = (\is_callable($param['validator'])) ? call_user_func_array($param['validator'], $this->app->getResources($param['injections'])) : $param['validator'];
$validator = (\is_callable($param['validator'])) ? call_user_func_array($param['validator'], $this->http->getResources($param['injections'])) : $param['validator'];
$node = [
'name' => $name,
@@ -293,11 +293,11 @@ class OpenAPI3 extends Format
}
switch ((!empty($validator)) ? \get_class($validator) : '') {
case 'Utopia\Validator\Text':
case 'Utopia\Http\Validator\Text':
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
break;
case 'Utopia\Validator\Boolean':
case 'Utopia\Http\Validator\Boolean':
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = false;
break;
@@ -322,14 +322,14 @@ class OpenAPI3 extends Format
$node['schema']['format'] = 'email';
$node['schema']['x-example'] = 'email@example.com';
break;
case 'Utopia\Validator\URL':
case 'Utopia\Http\Validator\URL':
$node['schema']['type'] = $validator->getType();
$node['schema']['format'] = 'url';
$node['schema']['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\JSON':
case 'Utopia\Validator\Mock':
case 'Utopia\Validator\Assoc':
case 'Utopia\Http\Validator\JSON':
case 'Utopia\Http\Validator\Mock':
case 'Utopia\Http\Validator\Assoc':
$param['default'] = (empty($param['default'])) ? new \stdClass() : $param['default'];
$node['schema']['type'] = 'object';
$node['schema']['x-example'] = '{}';
@@ -340,7 +340,7 @@ class OpenAPI3 extends Format
$node['schema']['type'] = $validator->getType();
$node['schema']['format'] = 'binary';
break;
case 'Utopia\Validator\ArrayList':
case 'Utopia\Http\Validator\ArrayList':
case 'Appwrite\Utopia\Database\Validator\Queries\Buckets':
case 'Appwrite\Utopia\Database\Validator\Queries\Collections':
case 'Appwrite\Utopia\Database\Validator\Queries\Indexes':
@@ -389,31 +389,31 @@ class OpenAPI3 extends Format
$node['schema']['format'] = 'phone';
$node['schema']['x-example'] = '+12065550100'; // In the US, 555 is reserved like example.com
break;
case 'Utopia\Validator\Range':
/** @var \Utopia\Validator\Range $validator */
case 'Utopia\Http\Validator\Range':
/** @var \Utopia\Http\Validator\Range $validator */
$node['schema']['type'] = $validator->getType() === Validator::TYPE_FLOAT ? 'number' : $validator->getType();
$node['schema']['format'] = $validator->getType() == Validator::TYPE_INTEGER ? 'int32' : 'float';
$node['schema']['x-example'] = $validator->getMin();
break;
case 'Utopia\Validator\Numeric':
case 'Utopia\Validator\Integer':
case 'Utopia\Http\Validator\Numeric':
case 'Utopia\Http\Validator\Integer':
$node['schema']['type'] = $validator->getType();
$node['schema']['format'] = 'int32';
break;
case 'Utopia\Validator\FloatValidator':
case 'Utopia\Http\Validator\FloatValidator':
$node['schema']['type'] = 'number';
$node['schema']['format'] = 'float';
break;
case 'Utopia\Validator\Length':
case 'Utopia\Http\Validator\Length':
$node['schema']['type'] = $validator->getType();
break;
case 'Utopia\Validator\Host':
case 'Utopia\Http\Validator\Host':
$node['schema']['type'] = $validator->getType();
$node['schema']['format'] = 'url';
$node['schema']['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\WhiteList':
/** @var \Utopia\Validator\WhiteList $validator */
case 'Utopia\Http\Validator\WhiteList':
/** @var \Utopia\Http\Validator\WhiteList $validator */
$node['schema']['type'] = $validator->getType();
$node['schema']['x-example'] = $validator->getList()[0];
+21 -21
View File
@@ -7,8 +7,8 @@ use Appwrite\Template\Template;
use Appwrite\Utopia\Response\Model;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Validator;
use Utopia\Validator\Nullable;
use Utopia\Http\Validator;
use Utopia\Http\Validator\Nullable;
class Swagger2 extends Format
{
@@ -113,7 +113,7 @@ class Swagger2 extends Format
$usedModels = [];
foreach ($this->routes as $route) {
/** @var \Utopia\Route $route */
/** @var \Utopia\Http\Route $route */
$url = \str_replace('/v1', '', $route->getPath());
$scope = $route->getLabel('scope', '');
$hide = $route->getLabel('sdk.hide', false);
@@ -271,8 +271,8 @@ class Swagger2 extends Format
);
foreach ($parameters as $name => $param) { // Set params
/** @var \Utopia\Validator $validator */
$validator = (\is_callable($param['validator'])) ? call_user_func_array($param['validator'], $this->app->getResources($param['injections'])) : $param['validator'];
/** @var \Utopia\Http\Validator $validator */
$validator = (\is_callable($param['validator'])) ? call_user_func_array($param['validator'], $this->http->getResources($param['injections'])) : $param['validator'];
$node = [
'name' => $name,
@@ -295,11 +295,11 @@ class Swagger2 extends Format
switch ((!empty($validator)) ? \get_class($validator) : '') {
case 'Utopia\Validator\Text':
case 'Utopia\Http\Validator\Text':
$node['type'] = $validator->getType();
$node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']';
break;
case 'Utopia\Validator\Boolean':
case 'Utopia\Http\Validator\Boolean':
$node['type'] = $validator->getType();
$node['x-example'] = false;
break;
@@ -324,14 +324,14 @@ class Swagger2 extends Format
$node['format'] = 'email';
$node['x-example'] = 'email@example.com';
break;
case 'Utopia\Validator\URL':
case 'Utopia\Http\Validator\URL':
$node['type'] = $validator->getType();
$node['format'] = 'url';
$node['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\JSON':
case 'Utopia\Validator\Mock':
case 'Utopia\Validator\Assoc':
case 'Utopia\Http\Validator\JSON':
case 'Utopia\Http\Validator\Mock':
case 'Utopia\Http\Validator\Assoc':
$node['type'] = 'object';
$node['default'] = (empty($param['default'])) ? new \stdClass() : $param['default'];
$node['x-example'] = '{}';
@@ -340,7 +340,7 @@ class Swagger2 extends Format
$consumes = ['multipart/form-data'];
$node['type'] = 'file';
break;
case 'Utopia\Validator\ArrayList':
case 'Utopia\Http\Validator\ArrayList':
case 'Appwrite\Utopia\Database\Validator\Queries\Buckets':
case 'Appwrite\Utopia\Database\Validator\Queries\Collections':
case 'Appwrite\Utopia\Database\Validator\Queries\Indexes':
@@ -392,31 +392,31 @@ class Swagger2 extends Format
$node['format'] = 'phone';
$node['x-example'] = '+12065550100';
break;
case 'Utopia\Validator\Range':
/** @var \Utopia\Validator\Range $validator */
case 'Utopia\Http\Validator\Range':
/** @var \Utopia\Http\Validator\Range $validator */
$node['type'] = $validator->getType() === Validator::TYPE_FLOAT ? 'number' : $validator->getType();
$node['format'] = $validator->getType() == Validator::TYPE_INTEGER ? 'int32' : 'float';
$node['x-example'] = $validator->getMin();
break;
case 'Utopia\Validator\Numeric':
case 'Utopia\Validator\Integer':
case 'Utopia\Http\Validator\Numeric':
case 'Utopia\Http\Validator\Integer':
$node['type'] = $validator->getType();
$node['format'] = 'int32';
break;
case 'Utopia\Validator\FloatValidator':
case 'Utopia\Http\Validator\FloatValidator':
$node['type'] = 'number';
$node['format'] = 'float';
break;
case 'Utopia\Validator\Length':
case 'Utopia\Http\Validator\Length':
$node['type'] = $validator->getType();
break;
case 'Utopia\Validator\Host':
case 'Utopia\Http\Validator\Host':
$node['type'] = $validator->getType();
$node['format'] = 'url';
$node['x-example'] = 'https://example.com';
break;
case 'Utopia\Validator\WhiteList':
/** @var \Utopia\Validator\WhiteList $validator */
case 'Utopia\Http\Validator\WhiteList':
/** @var \Utopia\Http\Validator\WhiteList $validator */
$node['type'] = $validator->getType();
$node['x-example'] = $validator->getList()[0];
+1 -1
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Task\Validator;
use Cron\CronExpression;
use Utopia\Validator;
use Utopia\Http\Validator;
class Cron extends Validator
{
@@ -2,7 +2,7 @@
namespace Appwrite\Usage\Calculators;
use Utopia\App;
use Utopia\Http\Http;
use Appwrite\Usage\Calculator;
use Utopia\Database\Database;
use Utopia\Database\Document;
+2 -2
View File
@@ -2,7 +2,7 @@
namespace Appwrite\Usage;
use Utopia\App;
use Utopia\Http\Http;
class Stats
{
@@ -83,7 +83,7 @@ class Stats
{
$projectId = $this->params['projectId'] ?? '';
$projectInternalId = $this->params['projectInternalId'];
$tags = ",projectInternalId={$projectInternalId},projectId={$projectId},version=" . App::getEnv('_APP_VERSION', 'UNKNOWN');
$tags = ",projectInternalId={$projectInternalId},projectId={$projectId},version=" . Http::getEnv('_APP_VERSION', 'UNKNOWN');
// the global namespace is prepended to every key (optional)
$this->statsd->setNamespace($this->namespace);
@@ -2,7 +2,7 @@
namespace Appwrite\Utopia\Database\Validator;
use Utopia\Validator;
use Utopia\Http\Validator;
class ProjectId extends Validator
{
+2 -2
View File
@@ -4,8 +4,8 @@ namespace Appwrite\Utopia;
use Appwrite\Utopia\Request\Filter;
use Swoole\Http\Request as SwooleRequest;
use Utopia\Route;
use Utopia\Swoole\Request as UtopiaRequest;
use Utopia\Http\Route;
use Utopia\Http\Adapter\Swoole\Request as UtopiaRequest;
class Request extends UtopiaRequest
{
+1 -2
View File
@@ -3,8 +3,7 @@
namespace Appwrite\Utopia;
use Exception;
use Swoole\Http\Request as SwooleRequest;
use Utopia\Swoole\Response as SwooleResponse;
use Utopia\Http\Adapter\Swoole\Response as SwooleResponse;
use Swoole\Http\Response as SwooleHTTPResponse;
use Utopia\Database\Document;
use Appwrite\Utopia\Response\Filter;
+333 -3
View File
@@ -2,10 +2,340 @@
namespace Appwrite\Utopia;
use Utopia\View as OldView;
use Exception;
class View extends OldView
class View
{
public const FILTER_ESCAPE = 'escape';
public const FILTER_NL2P = 'nl2p';
/**
* @var self|null
*/
protected ?self $parent = null;
/**
* @var string
*/
protected string $path = '';
/**
* @var bool
*/
protected bool $rendered = false;
/**
* @var array
*/
protected array $params = [];
/**
* @var array
*/
protected array $filters = [];
/**
* Constructor
*
* You can optionally initialize the View object with a template path, although this can also be set later using the $this->setPath($path) method
*
* @param string $path
*
* @throws Exception
*/
public function __construct(string $path = '')
{
$this->setPath($path);
$this
->addFilter(self::FILTER_ESCAPE, function (string $value) {
return \htmlentities($value, ENT_QUOTES, 'UTF-8');
})
->addFilter(self::FILTER_NL2P, function (string $value) {
$paragraphs = '';
foreach (\explode("\n\n", $value) as $line) {
if (\trim($line)) {
$paragraphs .= '<p>'.$line.'</p>';
}
}
$paragraphs = \str_replace("\n", '<br />', $paragraphs);
return $paragraphs;
});
}
/**
* Set param
*
* Assign a parameter by key
*
* @param string $key
* @param mixed $value
*
* @throws Exception
*/
public function setParam(string $key, mixed $value): static
{
if (\strpos($key, '.') !== false) {
throw new Exception('$key can\'t contain a dot "." character');
}
$this->params[$key] = $value;
return $this;
}
/**
* Set parent View object conatining this object
*
* @param self $view
*/
public function setParent(self $view): static
{
$this->parent = $view;
return $this;
}
/**
* Return a View instance of the parent view containing this view
*
* @return self|null
*/
public function getParent(): ?self
{
if (! empty($this->parent)) {
return $this->parent;
}
return null;
}
/**
* Get param
*
* Returns an assigned parameter by its key or $default if param key doesn't exists
*
* @param string $path
* @param mixed $default (optional)
* @return mixed
*/
public function getParam(string $path, mixed $default = null): mixed
{
$path = \explode('.', $path);
$temp = $this->params;
foreach ($path as $key) {
$temp = (isset($temp[$key])) ? $temp[$key] : null;
if (null !== $temp) {
$value = $temp;
} else {
return $default;
}
}
return $value;
}
/**
* Set path
*
* Set object template path that will be used to render view output
*
* @param string $path
*
* @throws Exception
*/
public function setPath(string $path): static
{
$this->path = $path;
return $this;
}
/**
* Set rendered
*
* By enabling rendered state to true, the object will not render its template and will return an empty string instead
*
* @param bool $state
*/
public function setRendered(bool $state = true): static
{
$this->rendered = $state;
return $this;
}
/**
* Is rendered
*
* Return whether current View rendering state is set to true or false
*
* @return bool
*/
public function isRendered(): bool
{
return $this->rendered;
}
/**
* Add Filter
*
* @param string $name
* @param callable $callback
*/
public function addFilter(string $name, callable $callback): static
{
$this->filters[$name] = $callback;
return $this;
}
/**
* Output and filter value
*
* @param mixed $value
* @param string|array $filter
* @return mixed
*
* @throws Exception
*/
public function print(mixed $value, string|array $filter = ''): mixed
{
if (! empty($filter)) {
if (\is_array($filter)) {
foreach ($filter as $callback) {
if (! isset($this->filters[$callback])) {
throw new Exception('Filter "'.$callback.'" is not registered');
}
$value = $this->filters[$callback]($value);
}
} else {
if (! isset($this->filters[$filter])) {
throw new Exception('Filter "'.$filter.'" is not registered');
}
$value = $this->filters[$filter]($value);
}
}
return $value;
}
/**
* Render
*
* Render view .phtml template file if template has not been set as rendered yet using $this->setRendered(true).
* In case path is not readable throws Exception.
*
* @param bool $minify
* @return string
*
* @throws Exception
*/
public function render(bool $minify = true): string
{
if ($this->rendered) { // Don't render any template
return '';
}
\ob_start(); //Start of build
if (\is_readable($this->path)) {
/**
* Include template file
*
* @psalm-suppress UnresolvableInclude
*/
include $this->path;
} else {
\ob_end_clean();
throw new Exception('"'.$this->path.'" view template is not readable');
}
$html = \ob_get_contents();
\ob_end_clean(); //End of build
if ($minify) {
// Searching textarea and pre
\preg_match_all('#\<textarea.*\>.*\<\/textarea\>#Uis', $html, $foundTxt);
\preg_match_all('#\<pre.*\>.*\<\/pre\>#Uis', $html, $foundPre);
// replacing both with <textarea>$index</textarea> / <pre>$index</pre>
$html = \str_replace($foundTxt[0], \array_map(function ($el) {
return '<textarea>'.$el.'</textarea>';
}, \array_keys($foundTxt[0])), $html);
$html = \str_replace($foundPre[0], \array_map(function ($el) {
return '<pre>'.$el.'</pre>';
}, \array_keys($foundPre[0])), $html);
// your stuff
$search = [
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
];
$replace = [
'>',
'<',
'\\1',
];
$html = \preg_replace($search, $replace, $html);
// Replacing back with content
$html = \str_replace(\array_map(function ($el) {
return '<textarea>'.$el.'</textarea>';
}, \array_keys($foundTxt[0])), $foundTxt[0], $html);
$html = \str_replace(\array_map(function ($el) {
return '<pre>'.$el.'</pre>';
}, \array_keys($foundPre[0])), $foundPre[0], $html);
}
return $html;
}
/* View Helpers */
/**
* Exec
*
* Exec child View components
*
* @param array|self $view
* @return string
*
* @throws Exception
*/
public function exec($view): string
{
$output = '';
if (\is_array($view)) {
foreach ($view as $node) { /* @var $node self */
if ($node instanceof self) {
$node->setParent($this);
$output .= $node->render();
}
}
}
if ($view instanceof self) {
$view->setParent($this);
$output = $view->render();
}
return $output;
}
/**
* Escape
*
@@ -19,4 +349,4 @@ class View extends OldView
{
return \htmlentities($str, ENT_QUOTES, 'UTF-8');
}
}
}
+3 -3
View File
@@ -3,7 +3,7 @@
namespace Appwrite\Vcs;
use Utopia\Database\Document;
use Utopia\App;
use Utopia\Http\Http;
class Comment
{
@@ -73,8 +73,8 @@ class Comment
$text .= "| Function | ID | Status | Action |\n";
$text .= "| :- | :- | :- | :- |\n";
$protocol = App::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https';
$hostname = App::getEnv('_APP_DOMAIN');
$protocol = Http::getEnv('_APP_OPTIONS_FORCE_HTTPS') == 'disabled' ? 'http' : 'https';
$hostname = Http::getEnv('_APP_DOMAIN');
foreach ($project['functions'] as $functionId => $function) {
$generateImage = function (string $status) use ($protocol, $hostname) {
+7 -7
View File
@@ -3,7 +3,7 @@
namespace Executor;
use Exception;
use Utopia\App;
use Utopia\Http\Http;
class Executor
{
@@ -34,11 +34,11 @@ class Executor
}
$this->endpoint = $endpoint;
$this->cpus = \intval(App::getEnv('_APP_FUNCTIONS_CPUS', '1'));
$this->memory = \intval(App::getEnv('_APP_FUNCTIONS_MEMORY', '512'));
$this->cpus = \intval(Http::getEnv('_APP_FUNCTIONS_CPUS', '1'));
$this->memory = \intval(Http::getEnv('_APP_FUNCTIONS_MEMORY', '512'));
$this->headers = [
'content-type' => 'application/json',
'authorization' => 'Bearer ' . App::getEnv('_APP_EXECUTOR_SECRET', ''),
'authorization' => 'Bearer ' . Http::getEnv('_APP_EXECUTOR_SECRET', ''),
'x-opr-addressing-method' => 'anycast-efficient'
];
}
@@ -86,7 +86,7 @@ class Executor
'version' => $version,
];
$timeout = (int) App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900);
$timeout = (int) Http::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900);
$response = $this->call(self::METHOD_POST, $route, [ 'x-opr-runtime-id' => $runtimeId ], $params, true, $timeout);
@@ -111,7 +111,7 @@ class Executor
string $projectId,
callable $callback
) {
$timeout = (int) App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900);
$timeout = (int) Http::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900);
$runtimeId = "$projectId-$deploymentId";
$route = "/runtimes/{$runtimeId}/logs";
@@ -179,7 +179,7 @@ class Executor
string $runtimeEntrypoint = null,
) {
if (empty($headers['host'])) {
$headers['host'] = App::getEnv('_APP_DOMAIN', '');
$headers['host'] = Http::getEnv('_APP_DOMAIN', '');
}
$runtimeId = "$projectId-$deploymentId";
+2 -2
View File
@@ -7,7 +7,7 @@ use Tests\E2E\Client;
use Tests\E2E\Scopes\ProjectCustom;
use Tests\E2E\Scopes\Scope;
use Tests\E2E\Scopes\SideNone;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
@@ -21,7 +21,7 @@ class AbuseTest extends Scope
{
parent::setUp();
if (App::getEnv('_APP_OPTIONS_ABUSE') === 'disabled') {
if (Http::getEnv('_APP_OPTIONS_ABUSE') === 'disabled') {
$this->markTestSkipped('Abuse is not enabled.');
}
}
+4 -4
View File
@@ -6,7 +6,7 @@ use Tests\E2E\Client;
use Tests\E2E\Scopes\ProjectCustom;
use Tests\E2E\Scopes\Scope;
use Tests\E2E\Scopes\SideServer;
use Utopia\App;
use Utopia\Http\Http;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
@@ -21,7 +21,7 @@ class AbuseTest extends Scope
{
parent::setUp();
if (App::getEnv('_APP_OPTIONS_ABUSE') === 'disabled') {
if (Http::getEnv('_APP_OPTIONS_ABUSE') === 'disabled') {
$this->markTestSkipped('Abuse is not enabled.');
}
}
@@ -90,7 +90,7 @@ class AbuseTest extends Scope
'x-appwrite-project' => $projectId,
], $this->getHeaders()), $graphQLPayload);
$max = App::getEnv('_APP_GRAPHQL_MAX_QUERY_COMPLEXITY', 250);
$max = Http::getEnv('_APP_GRAPHQL_MAX_QUERY_COMPLEXITY', 250);
$this->assertEquals('Max query complexity should be ' . $max . ' but got 259.', $response['body']['errors'][0]['message']);
}
@@ -98,7 +98,7 @@ class AbuseTest extends Scope
public function testTooManyQueriesBlocked()
{
$projectId = $this->getProject()['$id'];
$maxQueries = App::getEnv('_APP_GRAPHQL_MAX_QUERIES', 10);
$maxQueries = Http::getEnv('_APP_GRAPHQL_MAX_QUERIES', 10);
$query = [];
for ($i = 0; $i <= $maxQueries + 1; $i++) {
+3 -3
View File
@@ -5,7 +5,7 @@ namespace Tests\Unit\Event;
use Appwrite\Event\Event;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use Utopia\App;
use Utopia\Http\Http;
class EventTest extends TestCase
{
@@ -14,8 +14,8 @@ class EventTest extends TestCase
public function setUp(): void
{
$redisHost = App::getEnv('_APP_REDIS_HOST', '');
$redisPort = App::getEnv('_APP_REDIS_PORT', '');
$redisHost = Http::getEnv('_APP_REDIS_HOST', '');
$redisPort = Http::getEnv('_APP_REDIS_PORT', '');
\Resque::setBackend($redisHost . ':' . $redisPort);
$this->queue = 'v1-tests' . uniqid();
+3 -3
View File
@@ -4,7 +4,7 @@ namespace Tests\Unit\Usage;
use Appwrite\Usage\Stats;
use PHPUnit\Framework\TestCase;
use Utopia\App;
use Utopia\Http\Http;
class StatsTest extends TestCase
{
@@ -15,8 +15,8 @@ class StatsTest extends TestCase
public function setUp(): void
{
$host = App::getEnv('_APP_STATSD_HOST', 'telegraf');
$port = App::getEnv('_APP_STATSD_PORT', 8125);
$host = Http::getEnv('_APP_STATSD_HOST', 'telegraf');
$port = Http::getEnv('_APP_STATSD_PORT', 8125);
$connection = new \Domnikl\Statsd\Connection\UdpSocket($host, $port);
$statsd = new \Domnikl\Statsd\Client($connection);