Merge branch 'feat-database-indexing' of github.com:appwrite/appwrite into feat-db-refactor-routes

This commit is contained in:
kodumbeats 2021-06-14 10:40:05 -04:00
commit 24a5fb4867
44 changed files with 577 additions and 363 deletions

View file

@ -8,7 +8,10 @@
- Renamed *Devices* to *Sessions*
- Add Provider Icon to each Session
- Add Anonymous Account Placeholder
- Upgraded telegraf docker image version to v1.1.0
- Upgraded telegraf docker image version to v1.2.0
- Added new environment variables to the `telegraf` service:
- _APP_INFLUXDB_HOST
- _APP_INFLUXDB_PORT
## Bugs

View file

@ -629,7 +629,7 @@ $collections = [
'indexes' => [
[
'$id' => '_key_bucket',
'type' => Database::INDEX_UNIQUE,
'type' => Database::INDEX_KEY,
'attributes' => ['bucketId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
@ -852,7 +852,7 @@ $collections = [
'indexes' => [
[
'$id' => '_key_function',
'type' => Database::INDEX_UNIQUE,
'type' => Database::INDEX_KEY,
'attributes' => ['functionId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],
@ -960,7 +960,7 @@ $collections = [
'indexes' => [
[
'$id' => '_key_function',
'type' => Database::INDEX_UNIQUE,
'type' => Database::INDEX_KEY,
'attributes' => ['functionId'],
'lengths' => [Database::LENGTH_KEY],
'orders' => [Database::ORDER_ASC],

View file

@ -109,19 +109,20 @@ return [
'gitUserName' => 'appwrite',
],
[
'key' => 'kotlin',
'name' => 'Kotlin',
'url' => '',
'package' => '',
'enabled' => false,
'beta' => false,
'key' => 'android',
'name' => 'Android',
'version' => '0.0.0-SNAPSHOT',
'url' => 'https://github.com/appwrite/sdk-for-android',
'package' => 'https://repo1.maven.org/maven2/io/appwrite/sdk-for-android/',
'enabled' => true,
'beta' => true,
'dev' => false,
'hidden' => false,
'family' => APP_PLATFORM_CLIENT,
'prism' => 'kotlin',
'source' => false,
'gitUrl' => 'git@github.com:appwrite/sdk-for-kotlin.git',
'gitRepoName' => 'sdk-for-kotlin',
'source' => \realpath(__DIR__ . '/../sdks/client-android'),
'gitUrl' => 'git@github.com:appwrite/sdk-for-android.git',
'gitRepoName' => 'sdk-for-android',
'gitUserName' => 'appwrite',
],
// [

View file

@ -1,5 +1,6 @@
<?php
use Ahc\Jwt\JWT;
use Appwrite\Auth\Auth;
use Appwrite\Auth\Validator\Password;
use Appwrite\Detector\Detector;
@ -18,10 +19,8 @@ use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Validator\ArrayList;
use Utopia\Audit\Audit;
use Utopia\Audit\Adapters\MySQL as AuditAdapter;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Ahc\Jwt\JWT;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\UID;
@ -180,6 +179,7 @@ App::post('/v1/account/sessions')
$session = new Document(array_merge(
[
'$id' => $dbForInternal->getId(),
'userId' => $profile->getId(),
'provider' => Auth::SESSION_PROVIDER_EMAIL,
'providerUid' => $email,
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
@ -499,6 +499,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect')
$expiry = \time() + Auth::TOKEN_EXPIRATION_LOGIN_LONG;
$session = new Document(array_merge([
'$id' => $dbForInternal->getId(),
'userId' => $user->getId(),
'provider' => $provider,
'providerUid' => $oauth2ID,
'providerToken' => $accessToken,
@ -648,6 +649,7 @@ App::post('/v1/account/sessions/anonymous')
$session = new Document(array_merge(
[
'$id' => $dbForInternal->getId(),
'userId' => $user->getId(),
'provider' => Auth::SESSION_PROVIDER_ANONYMOUS,
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
'expire' => $expiry,
@ -833,22 +835,19 @@ App::get('/v1/account/logs')
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_LOG_LIST)
->inject('response')
->inject('register')
->inject('project')
->inject('user')
->inject('locale')
->inject('geodb')
->action(function ($response, $register, $project, $user, $locale, $geodb) {
->inject('dbForInternal')
->action(function ($response, $user, $locale, $geodb, $dbForInternal) {
/** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Document $project */
/** @var Utopia\Database\Document $user */
/** @var Utopia\Locale\Locale $locale */
/** @var MaxMind\Db\Reader $geodb */
/** @var Utopia\Database\Database $dbForInternal */
$adapter = new AuditAdapter($register->get('db'));
$adapter->setNamespace('app_'.$project->getId());
$audit = new Audit($adapter);
$audit = new Audit($dbForInternal);
$countries = $locale->getText('countries');
$logs = $audit->getLogsByUserAndActions($user->getId(), [
@ -879,7 +878,7 @@ App::get('/v1/account/logs')
$output[$i] = new Document(array_merge([
'event' => $log['event'],
'ip' => $log['ip'],
'time' => \strtotime($log['time']),
'time' => $log['time'],
], $detector->getOS(), $detector->getClient(), $detector->getDevice()));
$record = $geodb->get($log['ip']);
@ -1139,13 +1138,15 @@ App::delete('/v1/account/sessions/:sessionId')
->inject('response')
->inject('user')
->inject('dbForInternal')
->inject('locale')
->inject('audits')
->inject('events')
->action(function ($sessionId, $request, $response, $user, $dbForInternal, $audits, $events) {
->action(function ($sessionId, $request, $response, $user, $dbForInternal, $locale, $audits, $events) {
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Document $user */
/** @var Utopia\Database\Database $dbForInternal */
/** @var Utopia\Locale\Locale $locale */
/** @var Appwrite\Event\Event $audits */
/** @var Appwrite\Event\Event $events */
@ -1171,7 +1172,10 @@ App::delete('/v1/account/sessions/:sessionId')
$session->setAttribute('current', false);
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session->setAttribute('current', true);
$session
->setAttribute('current', true)
->setAttribute('countryName', (isset($countries[strtoupper($session->getAttribute('countryCode'))])) ? $countries[strtoupper($session->getAttribute('countryCode'))] : $locale->getText('locale.country.unknown'))
;
if (!Config::getParam('domainVerification')) {
$response
@ -1214,13 +1218,15 @@ App::delete('/v1/account/sessions')
->inject('response')
->inject('user')
->inject('dbForInternal')
->inject('locale')
->inject('audits')
->inject('events')
->action(function ($request, $response, $user, $dbForInternal, $audits, $events) {
->action(function ($request, $response, $user, $dbForInternal, $locale, $audits, $events) {
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Document $user */
/** @var Utopia\Database\Database $dbForInternal */
/** @var Utopia\Locale\Locale $locale */
/** @var Appwrite\Event\Event $audits */
/** @var Appwrite\Event\Event $events */
@ -1242,7 +1248,10 @@ App::delete('/v1/account/sessions')
;
}
$session->setAttribute('current', false);
$session
->setAttribute('current', false)
->setAttribute('countryName', (isset($countries[strtoupper($session->getAttribute('countryCode'))])) ? $countries[strtoupper($session->getAttribute('countryCode'))] : $locale->getText('locale.country.unknown'))
;
if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too
$session->setAttribute('current', true);
@ -1316,6 +1325,7 @@ App::post('/v1/account/recovery')
$secret = Auth::tokenGenerator();
$recovery = new Document([
'$id' => $dbForInternal->getId(),
'userId' => $profile->getId(),
'type' => Auth::TOKEN_TYPE_RECOVERY,
'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak
'expire' => \time() + Auth::TOKEN_EXPIRATION_RECOVERY,
@ -1499,6 +1509,7 @@ App::post('/v1/account/verification')
$verification = new Document([
'$id' => $dbForInternal->getId(),
'userId' => $user->getId(),
'type' => Auth::TOKEN_TYPE_VERIFICATION,
'secret' => Auth::hash($verificationSecret), // One way hash encryption to protect DB leak
'expire' => \time() + Auth::TOKEN_EXPIRATION_CONFIRM,
@ -1629,4 +1640,4 @@ App::put('/v1/account/verification')
;
$response->dynamic2($verification, Response::MODEL_TOKEN);
});
});

View file

@ -12,6 +12,7 @@ use Appwrite\Utopia\Response;
use Appwrite\Task\Validator\Cron;
use Utopia\App;
use Utopia\Exception;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
@ -499,13 +500,13 @@ App::get('/v1/functions/:functionId/tags')
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_TAG_LIST)
->param('functionId', '', new UID(), 'Function unique ID.')
// ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true)
->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true)
->param('limit', 25, new Range(0, 100), 'Results limit value. By default will return maximum 25 results. Maximum of 100 results allowed per request.', true)
->param('offset', 0, new Range(0, 2000), 'Results offset. The default value is 0. Use this param to manage pagination.', true)
// ->param('orderType', 'ASC', new WhiteList(['ASC', 'DESC'], true), 'Order result by ASC or DESC order.', true)
->param('orderType', 'ASC', new WhiteList(['ASC', 'DESC'], true), 'Order result by ASC or DESC order.', true)
->inject('response')
->inject('dbForInternal')
->action(function ($functionId, $limit, $offset, $response, $dbForInternal) {
->action(function ($functionId, $search, $limit, $offset, $orderType, $response, $dbForInternal) {
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Database $dbForInternal */
@ -517,7 +518,7 @@ App::get('/v1/functions/:functionId/tags')
$queries[] = new Query('functionId', Query::TYPE_EQUAL, [$function->getId()]);
$results = $dbForInternal->find('tags', $queries, $limit, $offset);
$results = $dbForInternal->find('tags', $queries, $limit, $offset, ['_id'], [$orderType]);
$sum = $dbForInternal->count('tags', $queries, APP_LIMIT_COUNT);
$response->dynamic2(new Document([
@ -759,7 +760,7 @@ App::get('/v1/functions/:functionId/executions')
$results = $dbForInternal->find('executions', [
new Query('functionId', Query::TYPE_EQUAL, [$function->getId()]),
], $limit, $offset);
], $limit, $offset, ['_id'], [Database::ORDER_DESC]);
$sum = $dbForInternal->count('executions', [
new Query('functionId', Query::TYPE_EQUAL, [$function->getId()]),

View file

@ -1,25 +1,27 @@
<?php
use Utopia\App;
use Utopia\Exception;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Boolean;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Appwrite\Network\Validator\URL;
use Utopia\Validator\Range;
use Utopia\Validator\Integer;
use Utopia\Config\Config;
use Utopia\Domains\Domain;
use Appwrite\Auth\Auth;
use Appwrite\Task\Validator\Cron;
use Appwrite\Network\Validator\CNAME;
use Appwrite\Network\Validator\Domain as DomainValidator;
use Appwrite\Network\Validator\URL;
use Appwrite\Task\Validator\Cron;
use Appwrite\Utopia\Response;
use Cron\CronExpression;
use Utopia\App;
use Utopia\Config\Config;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\UID;
use Utopia\Domains\Domain;
use Utopia\Exception;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Boolean;
use Utopia\Validator\Integer;
use Utopia\Validator\Range;
use Utopia\Validator\Text;
use Utopia\Validator\WhiteList;
use Utopia\Audit\Audit;
use Utopia\Abuse\Adapters\TimeLimit;
App::post('/v1/projects')
->desc('Create Project')
@ -62,8 +64,8 @@ App::post('/v1/projects')
$project = $dbForConsole->createDocument('projects', new Document([
'$collection' => 'projects',
'$read' => ['team:'.$teamId],
'$write' => ['team:'.$teamId.'/owner', 'team:'.$teamId.'/developer'],
'$read' => ['team:' . $teamId],
'$write' => ['team:' . $teamId . '/owner', 'team:' . $teamId . '/developer'],
'name' => $name,
'description' => $description,
'logo' => $logo,
@ -89,11 +91,17 @@ App::post('/v1/projects')
$collections = Config::getParam('collections2', []); /** @var array $collections */
$dbForInternal->setNamespace('project_'.$project->getId().'_internal');
$dbForInternal->setNamespace('project_' . $project->getId() . '_internal');
$dbForInternal->create();
$dbForExternal->setNamespace('project_'.$project->getId().'_external');
$dbForExternal->setNamespace('project_' . $project->getId() . '_external');
$dbForExternal->create();
$audit = new Audit($dbForInternal);
$audit->setup();
$adapter = new TimeLimit("", 0, 1, $dbForInternal);
$adapter->setup();
foreach ($collections as $key => $collection) {
$dbForInternal->createCollection($key);
@ -150,7 +158,7 @@ App::get('/v1/projects')
$queries = ($search) ? [new Query('name', Query::TYPE_SEARCH, [$search])] : [];
$results = $dbForConsole->find('projects', $queries, $limit, $offset);
$results = $dbForConsole->find('projects', $queries, $limit, $offset, ['_id'], [$orderType]);
$sum = $dbForConsole->count('projects', $queries, APP_LIMIT_COUNT);
$response->dynamic2(new Document([
@ -210,7 +218,7 @@ App::get('/v1/projects/:projectId/usage')
throw new Exception('Project not found', 404);
}
if(App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$period = [
'24h' => [
@ -234,44 +242,44 @@ App::get('/v1/projects/:projectId/usage')
'group' => '1d',
],
];
$client = $register->get('influxdb');
$requests = [];
$network = [];
$functions = [];
if ($client) {
$start = $period[$range]['start']->format(DateTime::RFC3339);
$end = $period[$range]['end']->format(DateTime::RFC3339);
$database = $client->selectDB('telegraf');
// Requests
$result = $database->query('SELECT sum(value) AS "value" FROM "appwrite_usage_requests_all" WHERE time > \''.$start.'\' AND time < \''.$end.'\' AND "metric_type"=\'counter\' AND "project"=\''.$project->getId().'\' GROUP BY time('.$period[$range]['group'].') FILL(null)');
$result = $database->query('SELECT sum(value) AS "value" FROM "appwrite_usage_requests_all" WHERE time > \'' . $start . '\' AND time < \'' . $end . '\' AND "metric_type"=\'counter\' AND "project"=\'' . $project->getId() . '\' GROUP BY time(' . $period[$range]['group'] . ') FILL(null)');
$points = $result->getPoints();
foreach ($points as $point) {
$requests[] = [
'value' => (!empty($point['value'])) ? $point['value'] : 0,
'date' => \strtotime($point['time']),
];
}
// Network
$result = $database->query('SELECT sum(value) AS "value" FROM "appwrite_usage_network_all" WHERE time > \''.$start.'\' AND time < \''.$end.'\' AND "metric_type"=\'counter\' AND "project"=\''.$project->getId().'\' GROUP BY time('.$period[$range]['group'].') FILL(null)');
$result = $database->query('SELECT sum(value) AS "value" FROM "appwrite_usage_network_all" WHERE time > \'' . $start . '\' AND time < \'' . $end . '\' AND "metric_type"=\'counter\' AND "project"=\'' . $project->getId() . '\' GROUP BY time(' . $period[$range]['group'] . ') FILL(null)');
$points = $result->getPoints();
foreach ($points as $point) {
$network[] = [
'value' => (!empty($point['value'])) ? $point['value'] : 0,
'date' => \strtotime($point['time']),
];
}
// Functions
$result = $database->query('SELECT sum(value) AS "value" FROM "appwrite_usage_executions_all" WHERE time > \''.$start.'\' AND time < \''.$end.'\' AND "metric_type"=\'counter\' AND "project"=\''.$project->getId().'\' GROUP BY time('.$period[$range]['group'].') FILL(null)');
$result = $database->query('SELECT sum(value) AS "value" FROM "appwrite_usage_executions_all" WHERE time > \'' . $start . '\' AND time < \'' . $end . '\' AND "metric_type"=\'counter\' AND "project"=\'' . $project->getId() . '\' GROUP BY time(' . $period[$range]['group'] . ') FILL(null)');
$points = $result->getPoints();
foreach ($points as $point) {
$functions[] = [
'value' => (!empty($point['value'])) ? $point['value'] : 0,
@ -285,14 +293,13 @@ App::get('/v1/projects/:projectId/usage')
$functions = [];
}
// Users
$projectDB->getCollection([
'limit' => 0,
'offset' => 0,
'filters' => [
'$collection=users'
'$collection=users',
],
]);
@ -317,7 +324,7 @@ App::get('/v1/projects/:projectId/usage')
'limit' => 0,
'offset' => 0,
'filters' => [
'$collection='.$collection['$id'],
'$collection=' . $collection['$id'],
],
]);
@ -373,7 +380,7 @@ App::get('/v1/projects/:projectId/usage')
'$collection=files',
],
]
) +
) +
$projectDB->getCount(
[
'attribute' => 'size',
@ -420,16 +427,16 @@ App::patch('/v1/projects/:projectId')
}
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('name', $name)
->setAttribute('description', $description)
->setAttribute('logo', $logo)
->setAttribute('url', $url)
->setAttribute('legalName', $legalName)
->setAttribute('legalCountry', $legalCountry)
->setAttribute('legalState', $legalState)
->setAttribute('legalCity', $legalCity)
->setAttribute('legalAddress', $legalAddress)
->setAttribute('legalTaxId', $legalTaxId)
->setAttribute('name', $name)
->setAttribute('description', $description)
->setAttribute('logo', $logo)
->setAttribute('url', $url)
->setAttribute('legalName', $legalName)
->setAttribute('legalCountry', $legalCountry)
->setAttribute('legalState', $legalState)
->setAttribute('legalCity', $legalCity)
->setAttribute('legalAddress', $legalAddress)
->setAttribute('legalTaxId', $legalTaxId)
);
$response->dynamic2($project, Response::MODEL_PROJECT);
@ -462,8 +469,8 @@ App::patch('/v1/projects/:projectId/oauth2')
}
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('usersOauth2'.\ucfirst($provider).'Appid', $appId)
->setAttribute('usersOauth2'.\ucfirst($provider).'Secret', $secret)
->setAttribute('usersOauth2' . \ucfirst($provider) . 'Appid', $appId)
->setAttribute('usersOauth2' . \ucfirst($provider) . 'Secret', $secret)
);
$response->dynamic2($project, Response::MODEL_PROJECT);
@ -494,7 +501,7 @@ App::patch('/v1/projects/:projectId/auth/limit')
}
$dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('usersAuthLimit', $limit)
->setAttribute('usersAuthLimit', $limit)
);
$response->dynamic2($project, Response::MODEL_PROJECT);
@ -511,7 +518,7 @@ App::patch('/v1/projects/:projectId/auth/:method')
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_PROJECT)
->param('projectId', '', new UID(), 'Project unique ID.')
->param('method', '', new WhiteList(\array_keys(Config::getParam('auth')), true), 'Auth Method. Possible values: '.implode(',', \array_keys(Config::getParam('auth'))), false)
->param('method', '', new WhiteList(\array_keys(Config::getParam('auth')), true), 'Auth Method. Possible values: ' . implode(',', \array_keys(Config::getParam('auth'))), false)
->param('status', false, new Boolean(true), 'Set the status of this auth method.')
->inject('response')
->inject('dbForConsole')
@ -529,7 +536,7 @@ App::patch('/v1/projects/:projectId/auth/:method')
}
$dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute($authKey, $status)
->setAttribute($authKey, $status)
);
$response->dynamic2($project, Response::MODEL_PROJECT);
@ -570,7 +577,7 @@ App::delete('/v1/projects/:projectId')
->setParam('type', DELETE_TYPE_DOCUMENT)
->setParam('document', $project)
;
if (!$dbForConsole->deleteDocument('teams', $project->getAttribute('teamId', null))) {
throw new Exception('Failed to remove project team from DB', 500);
}
@ -626,7 +633,7 @@ App::post('/v1/projects/:projectId/webhooks')
]);
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('webhooks', $webhook, Document::SET_TYPE_APPEND)
->setAttribute('webhooks', $webhook, Document::SET_TYPE_APPEND)
);
$response->setStatusCode(Response::STATUS_CODE_CREATED);
@ -736,16 +743,16 @@ App::put('/v1/projects/:projectId/webhooks/:webhookId')
}
$project->findAndReplace('$id', $webhook->getId(), $webhook
->setAttribute('name', $name)
->setAttribute('events', $events)
->setAttribute('url', $url)
->setAttribute('security', $security)
->setAttribute('httpUser', $httpUser)
->setAttribute('httpPass', $httpPass)
, 'webhooks');
->setAttribute('name', $name)
->setAttribute('events', $events)
->setAttribute('url', $url)
->setAttribute('security', $security)
->setAttribute('httpUser', $httpUser)
->setAttribute('httpPass', $httpPass)
, 'webhooks');
$dbForConsole->updateDocument('projects', $project->getId(), $project);
$response->dynamic2($webhook, Response::MODEL_WEBHOOK);
});
@ -816,7 +823,7 @@ App::post('/v1/projects/:projectId/keys')
]);
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('keys', $key, Document::SET_TYPE_APPEND)
->setAttribute('keys', $key, Document::SET_TYPE_APPEND)
);
$response->setStatusCode(Response::STATUS_CODE_CREATED);
@ -839,7 +846,7 @@ App::get('/v1/projects/:projectId/keys')
->action(function ($projectId, $response, $dbForConsole) {
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Database $dbForConsole */
$project = $dbForConsole->getDocument('projects', $projectId);
if ($project->isEmpty()) {
@ -917,12 +924,12 @@ App::put('/v1/projects/:projectId/keys/:keyId')
}
$project->findAndReplace('$id', $key->getId(), $key
->setAttribute('name', $name)
->setAttribute('scopes', $scopes)
, 'keys');
->setAttribute('name', $name)
->setAttribute('scopes', $scopes)
, 'keys');
$dbForConsole->updateDocument('projects', $project->getId(), $project);
$response->dynamic2($key, Response::MODEL_KEY);
});
@ -1015,7 +1022,7 @@ App::post('/v1/projects/:projectId/tasks')
]);
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('tasks', $task, Document::SET_TYPE_APPEND)
->setAttribute('tasks', $task, Document::SET_TYPE_APPEND)
);
if ($next) {
@ -1135,18 +1142,18 @@ App::put('/v1/projects/:projectId/tasks/:taskId')
$security = ($security === '1' || $security === 'true' || $security === 1 || $security === true);
$project->findAndReplace('$id', $task->getId(), $task
->setAttribute('name', $name)
->setAttribute('status', $status)
->setAttribute('schedule', $schedule)
->setAttribute('updated', \time())
->setAttribute('next', $next)
->setAttribute('security', $security)
->setAttribute('httpMethod', $httpMethod)
->setAttribute('httpUrl', $httpUrl)
->setAttribute('httpHeaders', $httpHeaders)
->setAttribute('httpUser', $httpUser)
->setAttribute('httpPass', $httpPass)
, 'tasks');
->setAttribute('name', $name)
->setAttribute('status', $status)
->setAttribute('schedule', $schedule)
->setAttribute('updated', \time())
->setAttribute('next', $next)
->setAttribute('security', $security)
->setAttribute('httpMethod', $httpMethod)
->setAttribute('httpUrl', $httpUrl)
->setAttribute('httpHeaders', $httpHeaders)
->setAttribute('httpUser', $httpUser)
->setAttribute('httpPass', $httpPass)
, 'tasks');
$dbForConsole->updateDocument('projects', $project->getId(), $project);
@ -1231,13 +1238,13 @@ App::post('/v1/projects/:projectId/platforms')
]);
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('platforms', $platform, Document::SET_TYPE_APPEND)
->setAttribute('platforms', $platform, Document::SET_TYPE_APPEND)
);
$response->setStatusCode(Response::STATUS_CODE_CREATED);
$response->dynamic2($platform, Response::MODEL_PLATFORM);
});
App::get('/v1/projects/:projectId/platforms')
->desc('List Platforms')
->groups(['api', 'projects'])
@ -1345,12 +1352,12 @@ App::put('/v1/projects/:projectId/platforms/:platformId')
;
$project->findAndReplace('$id', $platform->getId(), $platform
->setAttribute('name', $name)
->setAttribute('dateUpdated', \time())
->setAttribute('key', $key)
->setAttribute('store', $store)
->setAttribute('hostname', $hostname)
, 'platforms');
->setAttribute('name', $name)
->setAttribute('dateUpdated', \time())
->setAttribute('key', $key)
->setAttribute('store', $store)
->setAttribute('hostname', $hostname)
, 'platforms');
$dbForConsole->updateDocument('projects', $project->getId(), $project);
@ -1424,7 +1431,7 @@ App::post('/v1/projects/:projectId/domains')
$target = new Domain(App::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.', 500);
throw new Exception('Unreachable CNAME target (' . $target->get() . '), please use a domain with a public suffix.', 500);
}
$domain = new Domain($domain);
@ -1440,7 +1447,7 @@ App::post('/v1/projects/:projectId/domains')
]);
$project = $dbForConsole->updateDocument('projects', $project->getId(), $project
->setAttribute('domains', $domain, Document::SET_TYPE_APPEND)
->setAttribute('domains', $domain, Document::SET_TYPE_APPEND)
);
$response->setStatusCode(Response::STATUS_CODE_CREATED);
@ -1471,7 +1478,7 @@ App::get('/v1/projects/:projectId/domains')
}
$domains = $project->getAttribute('domains', []);
$response->dynamic2(new Document([
'domains' => $domains,
'sum' => count($domains),
@ -1544,7 +1551,7 @@ App::patch('/v1/projects/:projectId/domains/:domainId/verification')
$target = new Domain(App::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.', 500);
throw new Exception('Unreachable CNAME target (' . $target->get() . '), please use a domain with a public suffix.', 500);
}
if ($domain->getAttribute('verification') === true) {
@ -1558,8 +1565,8 @@ App::patch('/v1/projects/:projectId/domains/:domainId/verification')
}
$project->findAndReplace('$id', $domain->getId(), $domain
->setAttribute('verification', true)
, 'domains');
->setAttribute('verification', true)
, 'domains');
$dbForConsole->updateDocument('projects', $project->getId(), $project);
@ -1610,4 +1617,4 @@ App::delete('/v1/projects/:projectId/domains/:domainId')
;
$response->noContent();
});
});

View file

@ -225,6 +225,7 @@ App::get('/v1/storage/files/:fileId/preview')
->param('fileId', '', new UID(), 'File unique ID')
->param('width', 0, new Range(0, 4000), 'Resize preview image width, Pass an integer between 0 to 4000.', true)
->param('height', 0, new Range(0, 4000), 'Resize preview image height, Pass an integer between 0 to 4000.', true)
->param('gravity', Image::GRAVITY_CENTER, new WhiteList([Image::GRAVITY_CENTER, Image::GRAVITY_NORTH, Image::GRAVITY_NORTHWEST, Image::GRAVITY_NORTHEAST, Image::GRAVITY_WEST, Image::GRAVITY_EAST, Image::GRAVITY_SOUTHWEST, Image::GRAVITY_SOUTH, Image::GRAVITY_SOUTHEAST]), 'Image crop gravity', true)
->param('quality', 100, new Range(0, 100), 'Preview image quality. Pass an integer between 0 to 100. Defaults to 100.', true)
->param('borderWidth', 0, new Range(0, 100), 'Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0.', true)
->param('borderColor', '', new HexColor(), 'Preview image border color. Use a valid HEX color, no # is needed for prefix.', true)
@ -237,7 +238,7 @@ App::get('/v1/storage/files/:fileId/preview')
->inject('response')
->inject('project')
->inject('dbForInternal')
->action(function ($fileId, $width, $height, $quality, $borderWidth, $borderColor, $borderRadius, $opacity, $rotation, $background, $output, $request, $response, $project, $dbForInternal) {
->action(function ($fileId, $width, $height, $gravity, $quality, $borderWidth, $borderColor, $borderRadius, $opacity, $rotation, $background, $output, $request, $response, $project, $dbForInternal) {
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Document $project */
@ -325,7 +326,7 @@ App::get('/v1/storage/files/:fileId/preview')
$image = new Image($source);
$image->crop((int) $width, (int) $height);
$image->crop((int) $width, (int) $height, $gravity);
if (!empty($opacity) || $opacity==0) {
$image->setOpacity($opacity);

View file

@ -436,7 +436,7 @@ App::get('/v1/teams/:teamId/memberships')
throw new Exception('Team not found', 404);
}
$memberships = $dbForInternal->find('memberships', [new Query('teamId', Query::TYPE_EQUAL, [$teamId])], $limit, $offset);
$memberships = $dbForInternal->find('memberships', [new Query('teamId', Query::TYPE_EQUAL, [$teamId])], $limit, $offset, ['_id'], [$orderType]);
$sum = $dbForInternal->count('memberships', [new Query('teamId', Query::TYPE_EQUAL, [$teamId])], APP_LIMIT_COUNT);
$users = [];

View file

@ -13,7 +13,6 @@ use Utopia\Validator\Text;
use Utopia\Validator\Range;
use Utopia\Validator\Boolean;
use Utopia\Audit\Audit;
use Utopia\Audit\Adapters\MySQL as AuditAdapter;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Database\Validator\UID;
@ -90,7 +89,7 @@ App::get('/v1/users')
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Database\Database $dbForInternal */
$results = $dbForInternal->find('users', [], $limit, $offset);
$results = $dbForInternal->find('users', [], $limit, $offset, ['_id'], [$orderType]);
$sum = $dbForInternal->count('users', [], APP_LIMIT_COUNT);
$response->dynamic2(new Document([
@ -214,12 +213,10 @@ App::get('/v1/users/:userId/logs')
->label('sdk.response.model', Response::MODEL_LOG_LIST)
->param('userId', '', new UID(), 'User unique ID.')
->inject('response')
->inject('register')
->inject('project')
->inject('dbForInternal')
->inject('locale')
->inject('geodb')
->action(function ($userId, $response, $register, $project, $dbForInternal, $locale, $geodb) {
->action(function ($userId, $response, $dbForInternal, $locale, $geodb) {
/** @var Appwrite\Utopia\Response $response */
/** @var Utopia\Registry\Registry $register */
/** @var Appwrite\Database\Document $project */
@ -233,10 +230,7 @@ App::get('/v1/users/:userId/logs')
throw new Exception('User not found', 404);
}
$adapter = new AuditAdapter($register->get('db'));
$adapter->setNamespace('app_'.$project->getId());
$audit = new Audit($adapter);
$audit = new Audit($dbForInternal);
$countries = $locale->getText('countries');
@ -285,7 +279,7 @@ App::get('/v1/users/:userId/logs')
$output[$i] = new Document([
'event' => $log['event'],
'ip' => $log['ip'],
'time' => \strtotime($log['time']),
'time' => $log['time'],
'osCode' => $osCode,
'osName' => $osName,

View file

@ -9,7 +9,7 @@ use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\Storage\Device\Local;
use Utopia\Storage\Storage;
App::init(function ($utopia, $request, $response, $project, $user, $register, $events, $audits, $usage, $deletes) {
App::init(function ($utopia, $request, $response, $project, $user, $register, $events, $audits, $usage, $deletes, $dbForInternal) {
/** @var Utopia\App $utopia */
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
@ -21,6 +21,7 @@ App::init(function ($utopia, $request, $response, $project, $user, $register, $e
/** @var Appwrite\Event\Event $usage */
/** @var Appwrite\Event\Event $deletes */
/** @var Appwrite\Event\Event $functions */
/** @var Utopia\Database\Database $dbForInternal */
Storage::setDevice('files', new Local(APP_STORAGE_UPLOADS.'/app-'.$project->getId()));
Storage::setDevice('functions', new Local(APP_STORAGE_FUNCTIONS.'/app-'.$project->getId()));
@ -31,47 +32,44 @@ App::init(function ($utopia, $request, $response, $project, $user, $register, $e
throw new Exception('Missing or unknown project ID', 400);
}
// /*
// * Abuse Check
// */
// $timeLimit = new TimeLimit($route->getLabel('abuse-key', 'url:{url},ip:{ip}'), $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), function () use ($register) {
// return $register->get('db');
// });
// $timeLimit->setNamespace('app_'.$project->getId());
// $timeLimit
// ->setParam('{userId}', $user->getId())
// ->setParam('{userAgent}', $request->getUserAgent(''))
// ->setParam('{ip}', $request->getIP())
// ->setParam('{url}', $request->getHostname().$route->getURL())
// ;
/*
* Abuse Check
*/
$timeLimit = new TimeLimit($route->getLabel('abuse-key', 'url:{url},ip:{ip}'), $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForInternal);
$timeLimit
->setParam('{userId}', $user->getId())
->setParam('{userAgent}', $request->getUserAgent(''))
->setParam('{ip}', $request->getIP())
->setParam('{url}', $request->getHostname().$route->getURL())
;
// //TODO make sure we get array here
//TODO make sure we get array here
// 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 ($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);
$abuse = new Abuse($timeLimit);
// if ($timeLimit->limit()) {
// $response
// ->addHeader('X-RateLimit-Limit', $timeLimit->limit())
// ->addHeader('X-RateLimit-Remaining', $timeLimit->remaining())
// ->addHeader('X-RateLimit-Reset', $timeLimit->time() + $route->getLabel('abuse-time', 3600))
// ;
// }
if ($timeLimit->limit()) {
$response
->addHeader('X-RateLimit-Limit', $timeLimit->limit())
->addHeader('X-RateLimit-Remaining', $timeLimit->remaining())
->addHeader('X-RateLimit-Reset', $timeLimit->time() + $route->getLabel('abuse-time', 3600))
;
}
// $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::$roles);
// $isAppUser = Auth::isAppUser(Authorization::$roles);
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::$roles);
$isAppUser = Auth::isAppUser(Authorization::$roles);
// if (($abuse->check() // Route is rate-limited
// && App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled') // Abuse is not diabled
// && (!$isAppUser && !$isPrivilegedUser)) // User is not an admin or API key
// {
// throw new Exception('Too many requests', 429);
// }
if (($abuse->check() // Route is rate-limited
&& App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled') // Abuse is not disabled
&& (!$isAppUser && !$isPrivilegedUser)) // User is not an admin or API key
{
throw new Exception('Too many requests', 429);
}
/*
* Background Jobs
@ -111,7 +109,7 @@ App::init(function ($utopia, $request, $response, $project, $user, $register, $e
->setParam('projectId', $project->getId())
;
}, ['utopia', 'request', 'response', 'project', 'user', 'register', 'events', 'audits', 'usage', 'deletes'], 'api');
}, ['utopia', 'request', 'response', 'project', 'user', 'register', 'events', 'audits', 'usage', 'deletes', 'dbForInternal'], 'api');
App::init(function ($utopia, $request, $response, $project, $user) {

View file

@ -233,6 +233,7 @@ App::get('/specs/:format')
->groups(['web', 'home'])
->label('scope', 'public')
->label('docs', false)
->label('origin', '*')
->param('format', 'swagger2', new WhiteList(['swagger2', 'open-api3'], true), 'Spec format.', true)
->param('platform', APP_PLATFORM_CLIENT, new WhiteList([APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER, APP_PLATFORM_CONSOLE], true), 'Choose target platform.', true)
->param('tests', 0, function () {return new Range(0, 1);}, 'Include only test services.', true)

View file

@ -3,8 +3,6 @@
require_once __DIR__.'/../vendor/autoload.php';
use Appwrite\Database\Validator\Authorization;
use Utopia\Swoole\Files;
use Utopia\Swoole\Request;
use Appwrite\Utopia\Response;
use Swoole\Process;
use Swoole\Http\Server;
@ -14,6 +12,10 @@ use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Validator\Authorization as Authorization2;
use Utopia\Audit\Audit;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\Swoole\Files;
use Utopia\Swoole\Request;
// xdebug_start_trace('/tmp/trace');
@ -67,6 +69,12 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
$register->get('cache')->flushAll();
$dbForConsole->create();
$audit = new Audit($dbForConsole);
$audit->setup();
$adapter = new TimeLimit("", 0, 1, $dbForConsole);
$adapter->setup();
foreach ($collections as $key => $collection) {
$dbForConsole->createCollection($key);

View file

@ -15,7 +15,7 @@ use Appwrite\SDK\Language\Deno;
use Appwrite\SDK\Language\DotNet;
use Appwrite\SDK\Language\Flutter;
use Appwrite\SDK\Language\Go;
use Appwrite\SDK\Language\Java;
use Appwrite\SDK\Language\Kotlin;
use Appwrite\SDK\Language\Swift;
$cli
@ -134,9 +134,6 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
case 'go':
$config = new Go();
break;
case 'java':
$config = new Java();
break;
case 'swift':
$config = new Swift();
break;
@ -144,6 +141,9 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
$cover = '';
$config = new DotNet();
break;
case 'android':
$config = new Kotlin();
break;
default:
throw new Exception('Language "'.$language['key'].'" not supported');
break;
@ -155,9 +155,8 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
$sdk
->setName($language['name'])
->setDescription("Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way.
Use the {$language['name']} SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools.
For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs)")
->setNamespace('io appwrite')
->setDescription("Appwrite is an open-source backend as a service server that abstract and simplify complex and repetitive development tasks behind a very simple to use REST API. Appwrite aims to help you develop your apps faster and in a more secure way. Use the {$language['name']} SDK to integrate your app with the Appwrite server to easily start interacting with all of Appwrite backend APIs and tools. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs)")
->setShortDescription('Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API')
->setLicense($license)
->setLicenseContent($licenseContent)

View file

@ -240,11 +240,11 @@ $usageStatsEnabled = $this->getParam('usageStatsEnabled',true);
<li>
<div class="link flutter-new"><img src="/images/clients/flutter.png?v=<?php echo APP_CACHE_BUSTER; ?>" alt="Flutter Platform Logo" class="avatar xxs margin-end-small" loading="lazy" /> New Flutter App &nbsp;<span class="text-size-tiny">(beta)</span></div>
</li>
<li class="disabled">
<div class="link ios-new"><img src="/images/clients/ios.png?v=<?php echo APP_CACHE_BUSTER; ?>" alt="iOS Platform Logo" class="avatar xxs margin-end-small" loading="lazy" /> New iOS App <span class="text-fade text-size-small">(soon)</span></div>
<li>
<div class="link android-new"><img src="/images/clients/android.png?v=<?php echo APP_CACHE_BUSTER; ?>" alt="Android Platform Logo" class="avatar xxs margin-end-small" loading="lazy" /> New Android App</div>
</li>
<li class="disabled">
<div class="link android-new"><img src="/images/clients/android.png?v=<?php echo APP_CACHE_BUSTER; ?>" alt="Android Platform Logo" class="avatar xxs margin-end-small" loading="lazy" /> New Android App <span class="text-fade text-size-small">(soon)</span></div>
<div class="link ios-new"><img src="/images/clients/ios.png?v=<?php echo APP_CACHE_BUSTER; ?>" alt="iOS Platform Logo" class="avatar xxs margin-end-small" loading="lazy" /> New iOS App <span class="text-fade text-size-small">(soon)</span></div>
</li>
<li class="disabled">
<div class="link unity-new"><img src="/images/clients/unity.png?v=<?php echo APP_CACHE_BUSTER; ?>" alt="Unity Platform Logo" class="avatar xxs margin-end-small" loading="lazy" /> New Unity Game <span class="text-fade text-size-small">(soon)</span></div>
@ -329,6 +329,42 @@ $usageStatsEnabled = $this->getParam('usageStatsEnabled',true);
</form>
</script>
<div data-ui-modal class="modal box close" data-button-alias=".android-new">
<button type="button" class="close pull-end" data-ui-modal-close=""><i class="icon-cancel"></i></button>
<h1>Register your Android App</h1>
<form
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Create Project Platform (Android)"
data-service="projects.createPlatform"
data-scope="console"
data-event="submit"
data-success="alert,trigger,reset"
data-success-param-alert-text="Registered new platform successfully"
data-success-param-trigger-events="projects.createPlatform"
data-failure="alert"
data-failure-param-alert-text="Failed to register platform"
data-failure-param-alert-classname="error">
<input type="hidden" name="projectId" data-ls-bind="{{router.params.project}}" />
<input type="hidden" name="type" data-ls-bind="android" />
<label for="name">Name <span class="tooltip large" data-tooltip="Choose any name that will help you distinguish between your different apps."><i class="icon-question"></i></span></label>
<input type="text" class="full-width" name="name" required autocomplete="off" placeholder="My Android App" maxlength="128" />
<label for="key">Package Name <span class="tooltip large" data-tooltip="Your package name is generally the applicationId in your app-level build.gradle file."><i class="icon-question"></i></span></label>
<input type="text" class="full-width" name="key" required autocomplete="off" placeholder="com.company.appname" />
<hr />
<button type="submit">Register</button> &nbsp; <button data-ui-modal-close="" type="button" class="reverse">Back</button>
</form>
</div>
<div data-ui-modal class="modal box close width-large" data-button-alias=".flutter-new">
<button type="button" class="close pull-end" data-ui-modal-close=""><i class="icon-cancel"></i></button>

View file

@ -372,11 +372,14 @@ services:
- appwrite-influxdb:/var/lib/influxdb:rw
telegraf:
image: appwrite/telegraf:1.1.0
image: appwrite/telegraf:1.2.0
container_name: appwrite-telegraf
restart: unless-stopped
networks:
- appwrite
environment:
- _APP_INFLUXDB_HOST
- _APP_INFLUXDB_PORT
networks:
gateway:

View file

@ -1,24 +1,27 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\Audit\Audit;
use Utopia\Audit\Adapters\MySQL as AuditAdapter;
use Utopia\Cache\Adapter\Redis;
use Utopia\Cache\Cache;
use Utopia\CLI\Console;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Database;
require_once __DIR__.'/../init.php';
Console::title('Audits V1 Worker');
Console::success(APP_NAME.' audits worker v1 has started');
class AuditsV1
class AuditsV1 extends Worker
{
public $args = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
global $register;
@ -31,16 +34,17 @@ class AuditsV1
$data = $this->args['data'];
$db = $register->get('db', true);
$adapter = new AuditAdapter($db);
$adapter->setNamespace('app_'.$projectId);
$cache = new Cache(new Redis($register->get('cache')));
$dbForInternal = new Database(new MariaDB($db), $cache);
$dbForInternal->setNamespace('project_'.$projectId.'_internal');
$audit = new Audit($adapter);
$audit = new Audit($dbForInternal);
$audit->log($userId, $event, $resource, $userAgent, $ip, '', $data);
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
}
}

View file

@ -1,30 +1,30 @@
<?php
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Domains\Domain;
use Appwrite\Database\Database;
use Appwrite\Database\Adapter\MySQL as MySQLAdapter;
use Appwrite\Database\Adapter\Redis as RedisAdapter;
use Appwrite\Database\Validator\Authorization;
use Appwrite\Network\Validator\CNAME;
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Domains\Domain;
require_once __DIR__.'/../init.php';
Console::title('Certificates V1 Worker');
Console::success(APP_NAME.' certificates worker v1 has started');
class CertificatesV1
class CertificatesV1 extends Worker
{
public $args = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
global $register;
@ -204,8 +204,7 @@ class CertificatesV1
Authorization::reset();
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
}
}

View file

@ -1,45 +1,48 @@
<?php
use Appwrite\Database\Database;
use Utopia\Database\Database as Database2;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Appwrite\Database\Adapter\MySQL as MySQLAdapter;
use Appwrite\Database\Adapter\Redis as RedisAdapter;
use Appwrite\Database\Document;
use Appwrite\Database\Validator\Authorization;
use Appwrite\Resque\Worker;
use Utopia\Storage\Device\Local;
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Audit\Audit;
use Utopia\Audit\Adapters\MySQL as AuditAdapter;
use Utopia\Cache\Cache;
use Utopia\Database\Adapter\MariaDB;
require_once __DIR__.'/../init.php';
Console::title('Deletes V1 Worker');
Console::success(APP_NAME.' deletes worker v1 has started'."\n");
class DeletesV1
class DeletesV1 extends Worker
{
public $args = [];
protected $consoleDB = null;
public function setUp(): void
public function init(): void
{
}
public function perform()
{
$projectId = isset($this->args['projectId']) ? $this->args['projectId'] : '';
$type = $this->args['type'];
public function run(): void
{
$projectId = $this->args['projectId'] ?? '';
$type = $this->args['type'] ?? '';
switch (strval($type)) {
case DELETE_TYPE_DOCUMENT:
$document = $this->args['document'];
$document = $this->args['document'] ?? '';
$document = new Document($document);
switch (strval($document->getCollection())) {
switch ($document->getCollection()) {
case Database::SYSTEM_COLLECTION_PROJECTS:
$this->deleteProject($document);
break;
@ -78,13 +81,11 @@ class DeletesV1
default:
Console::error('No delete operation for type: '.$type);
break;
}
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
protected function deleteDocuments(Document $document, $projectId)
@ -167,12 +168,9 @@ class DeletesV1
throw new Exception('Failed to delete audit logs. No timestamp provided');
}
$timeLimit = new TimeLimit("", 0, 1, function () use ($register) {
return $register->get('db');
});
$this->deleteForProjectIds(function($projectId) use ($timeLimit, $timestamp){
$timeLimit->setNamespace('app_'.$projectId);
$this->deleteForProjectIds(function($projectId) use ($timestamp){
$timeLimit = new TimeLimit("", 0, 1, $this->getInternalDB($projectId));
$abuse = new Abuse($timeLimit);
$status = $abuse->cleanup($timestamp);
@ -189,9 +187,7 @@ class DeletesV1
throw new Exception('Failed to delete audit logs. No timestamp provided');
}
$this->deleteForProjectIds(function($projectId) use ($register, $timestamp){
$adapter = new AuditAdapter($register->get('db'));
$adapter->setNamespace('app_'.$projectId);
$audit = new Audit($adapter);
$audit = new Audit($this->getInternalDB($projectId));
$status = $audit->cleanup($timestamp);
if (!$status) {
throw new Exception('Failed to delete Audit logs for project'.$projectId);
@ -375,4 +371,18 @@ class DeletesV1
return $projectDB;
}
}
/**
* @return Database2
*/
protected function getInternalDB($projectId): Database2
{
global $register;
$cache = new Cache(new RedisCache($register->get('cache')));
$dbForInternal = new Database2(new MariaDB($register->get('db')), $cache);
$dbForInternal->setNamespace('project_'.$projectId.'_internal'); // Main DB
return $dbForInternal;
}
}

View file

@ -1,6 +1,7 @@
<?php
use Appwrite\Event\Event;
use Appwrite\Resque\Worker;
use Cron\CronExpression;
use Swoole\Runtime;
use Utopia\App;
@ -126,17 +127,17 @@ Console::info(count($list)." functions listed in " . ($executionEnd - $execution
//TODO aviod scheduled execution if delay is bigger than X offest
class FunctionsV1
class FunctionsV1 extends Worker
{
public $args = [];
public $allowed = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
global $register;
@ -563,7 +564,7 @@ class FunctionsV1
return $output;
}
public function tearDown(): void
public function shutdown(): void
{
}
}
}

View file

@ -1,26 +1,26 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\CLI\Console;
require_once __DIR__.'/../init.php';
Console::title('Mails V1 Worker');
Console::success(APP_NAME.' mails worker v1 has started'."\n");
class MailsV1
class MailsV1 extends Worker
{
/**
* @var array
*/
public $args = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
global $register;
@ -68,8 +68,7 @@ class MailsV1
}
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
}
}

View file

@ -1,32 +1,32 @@
<?php
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Appwrite\Database\Database;
use Appwrite\Database\Adapter\MySQL as MySQLAdapter;
use Appwrite\Database\Adapter\Redis as RedisAdapter;
use Appwrite\Database\Validator\Authorization;
use Appwrite\Resque\Worker;
use Cron\CronExpression;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
require_once __DIR__.'/../init.php';
Console::title('Tasks V1 Worker');
Console::success(APP_NAME.' tasks worker v1 has started');
class TasksV1
class TasksV1 extends Worker
{
/**
* @var array
*/
public $args = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
global $register;
@ -73,11 +73,11 @@ class TasksV1
}
if ($task->getAttribute('updated') !== $updated) { // Task have already been rescheduled by owner
return false;
return;
}
if ($task->getAttribute('status') !== 'play') { // Skip task and don't schedule again
return false;
return;
}
// Reschedule
@ -202,11 +202,10 @@ class TasksV1
// Send alert if needed (use SMTP as default for now)
return true;
return;
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
}
}

View file

@ -1,29 +1,30 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\CLI\Console;
require_once __DIR__.'/../init.php';
Console::title('Usage V1 Worker');
Console::success(APP_NAME.' usage worker v1 has started');
class UsageV1
class UsageV1 extends Worker
{
/**
* @var array
*/
public $args = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
global $register;
/** @var \Domnikl\Statsd\Client $statsd */
$statsd = $register->get('statsd', true);
$projectId = $this->args['projectId'] ?? '';
@ -36,12 +37,12 @@ class UsageV1
$httpMethod = $this->args['httpMethod'] ?? '';
$httpRequest = $this->args['httpRequest'] ?? 0;
$functionId = $this->args['functionId'];
$functionId = $this->args['functionId'] ?? '';
$functionExecution = $this->args['functionExecution'] ?? 0;
$functionExecutionTime = $this->args['functionExecutionTime'] ?? 0;
$functionStatus = $this->args['functionStatus'] ?? '';
$tags = ",project={$projectId},version=".App::getEnv('_APP_VERSION', 'UNKNOWN').'';
$tags = ",project={$projectId},version=".App::getEnv('_APP_VERSION', 'UNKNOWN');
// the global namespace is prepended to every key (optional)
$statsd->setNamespace('appwrite.usage');
@ -52,7 +53,6 @@ class UsageV1
if($functionExecution >= 1) {
$statsd->increment('executions.all'.$tags.',functionId='.$functionId.',functionStatus='.$functionStatus);
var_dump($tags.',functionId='.$functionId.',functionStatus='.$functionStatus);
$statsd->count('executions.time'.$tags.',functionId='.$functionId, $functionExecutionTime);
}
@ -65,8 +65,7 @@ class UsageV1
}
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
}
}

View file

@ -1,23 +1,23 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\CLI\Console;
require_once __DIR__.'/../init.php';
Console::title('Webhooks V1 Worker');
Console::success(APP_NAME.' webhooks worker v1 has started');
class WebhooksV1
class WebhooksV1 extends Worker
{
public $args = [];
public function setUp(): void
public function init(): void
{
}
public function perform()
public function run(): void
{
$errors = [];
@ -88,8 +88,7 @@ class WebhooksV1
}
}
public function tearDown(): void
public function shutdown(): void
{
// ... Remove environment for this job
}
}
}

View file

@ -39,9 +39,9 @@
"appwrite/php-runtimes": "0.2.*",
"utopia-php/framework": "0.14.*",
"utopia-php/abuse": "0.4.*",
"utopia-php/abuse": "dev-feat-utopia-db-integration",
"utopia-php/analytics": "0.2.*",
"utopia-php/audit": "0.5.*",
"utopia-php/audit": "dev-feat-utopia-db-integration",
"utopia-php/cache": "0.4.*",
"utopia-php/cli": "0.11.*",
"utopia-php/config": "0.2.*",
@ -52,7 +52,7 @@
"utopia-php/domains": "1.1.*",
"utopia-php/swoole": "0.2.*",
"utopia-php/storage": "0.5.*",
"utopia-php/image": "0.2.*",
"utopia-php/image": "0.3.*",
"resque/php-resque": "1.3.6",
"matomo/device-detector": "4.2.2",
"dragonmantank/cron-expression": "3.1.0",
@ -62,6 +62,16 @@
"adhocore/jwt": "1.1.2",
"slickdeals/statsd": "3.0.2"
},
"repositories": [
{
"type": "git",
"url": "https://github.com/lohanidamodar/audit"
},
{
"type": "git",
"url": "https://github.com/lohanidamodar/abuse"
}
],
"require-dev": {
"appwrite/sdk-generator": "0.10.11",
"swoole/ide-helper": "4.6.6",

109
composer.lock generated
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": "0456f223731164e0d43456a74949d8bf",
"content-hash": "bce8a47d7c5e94cc18bd05b1229ad1db",
"packages": [
{
"name": "adhocore/jwt",
@ -1603,21 +1603,16 @@
},
{
"name": "utopia-php/abuse",
"version": "0.4.1",
"version": "dev-feat-utopia-db-integration",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/abuse.git",
"reference": "8b7973aae4b02489bd22ffea45b985608f13b6d9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/abuse/zipball/8b7973aae4b02489bd22ffea45b985608f13b6d9",
"reference": "8b7973aae4b02489bd22ffea45b985608f13b6d9",
"shasum": ""
"url": "https://github.com/lohanidamodar/abuse",
"reference": "351dba60714321fabcd5028fdf7325f18f343018"
},
"require": {
"ext-pdo": "*",
"php": ">=7.4"
"php": ">=7.4",
"utopia-php/database": "0.3.*"
},
"require-dev": {
"phpunit/phpunit": "^9.4",
@ -1629,7 +1624,6 @@
"Utopia\\Abuse\\": "src/Abuse"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
@ -1641,17 +1635,13 @@
],
"description": "A simple abuse library to manage application usage limits",
"keywords": [
"Abuse",
"abuse",
"framework",
"php",
"upf",
"utopia"
],
"support": {
"issues": "https://github.com/utopia-php/abuse/issues",
"source": "https://github.com/utopia-php/abuse/tree/0.4.1"
},
"time": "2021-06-05T14:31:33+00:00"
"time": "2021-06-13T07:41:20+00:00"
},
{
"name": "utopia-php/analytics",
@ -1710,21 +1700,16 @@
},
{
"name": "utopia-php/audit",
"version": "0.5.1",
"version": "dev-feat-utopia-db-integration",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/audit.git",
"reference": "154a850170a58667a15e4b65fbabb6cd0b709dd9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/audit/zipball/154a850170a58667a15e4b65fbabb6cd0b709dd9",
"reference": "154a850170a58667a15e4b65fbabb6cd0b709dd9",
"shasum": ""
"url": "https://github.com/lohanidamodar/audit",
"reference": "b3ca9fa928fdec8c966596cbd85ee1141c79b6eb"
},
"require": {
"ext-pdo": "*",
"php": ">=7.1"
"php": ">=7.4",
"utopia-php/database": "0.3.*"
},
"require-dev": {
"phpunit/phpunit": "^9.3",
@ -1736,7 +1721,6 @@
"Utopia\\Audit\\": "src/Audit"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
@ -1748,17 +1732,13 @@
],
"description": "A simple audit library to manage application users logs",
"keywords": [
"Audit",
"audit",
"framework",
"php",
"upf",
"utopia"
],
"support": {
"issues": "https://github.com/utopia-php/audit/issues",
"source": "https://github.com/utopia-php/audit/tree/0.5.1"
},
"time": "2020-12-21T17:28:53+00:00"
"time": "2021-06-13T07:41:15+00:00"
},
{
"name": "utopia-php/cache",
@ -1919,16 +1899,16 @@
},
{
"name": "utopia-php/database",
"version": "0.3.1",
"version": "0.3.2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/database.git",
"reference": "6f8b7184ae4971672188607ea311a22a50da6767"
"reference": "8e56a2d399d17b2497c8ee0f8bf429ac2da90c56"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/database/zipball/6f8b7184ae4971672188607ea311a22a50da6767",
"reference": "6f8b7184ae4971672188607ea311a22a50da6767",
"url": "https://api.github.com/repos/utopia-php/database/zipball/8e56a2d399d17b2497c8ee0f8bf429ac2da90c56",
"reference": "8e56a2d399d17b2497c8ee0f8bf429ac2da90c56",
"shasum": ""
},
"require": {
@ -1976,9 +1956,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/database/issues",
"source": "https://github.com/utopia-php/database/tree/0.3.1"
"source": "https://github.com/utopia-php/database/tree/0.3.2"
},
"time": "2021-06-11T15:02:46+00:00"
"time": "2021-06-12T18:26:26+00:00"
},
{
"name": "utopia-php/domains",
@ -2085,16 +2065,16 @@
},
{
"name": "utopia-php/image",
"version": "0.2.1",
"version": "0.3.2",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/image.git",
"reference": "0754955a165483852184d1215cc3bf659432d23a"
"reference": "2044fdd44d87c4253cfe929cca975fd037461b00"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/image/zipball/0754955a165483852184d1215cc3bf659432d23a",
"reference": "0754955a165483852184d1215cc3bf659432d23a",
"url": "https://api.github.com/repos/utopia-php/image/zipball/2044fdd44d87c4253cfe929cca975fd037461b00",
"reference": "2044fdd44d87c4253cfe929cca975fd037461b00",
"shasum": ""
},
"require": {
@ -2132,9 +2112,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/image/issues",
"source": "https://github.com/utopia-php/image/tree/0.2.1"
"source": "https://github.com/utopia-php/image/tree/0.3.2"
},
"time": "2021-04-13T07:47:24+00:00"
"time": "2021-06-10T09:16:11+00:00"
},
{
"name": "utopia-php/locale",
@ -2983,20 +2963,20 @@
},
{
"name": "felixfbecker/advanced-json-rpc",
"version": "v3.2.0",
"version": "v3.2.1",
"source": {
"type": "git",
"url": "https://github.com/felixfbecker/php-advanced-json-rpc.git",
"reference": "06f0b06043c7438959dbdeed8bb3f699a19be22e"
"reference": "b5f37dbff9a8ad360ca341f3240dc1c168b45447"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/felixfbecker/php-advanced-json-rpc/zipball/06f0b06043c7438959dbdeed8bb3f699a19be22e",
"reference": "06f0b06043c7438959dbdeed8bb3f699a19be22e",
"url": "https://api.github.com/repos/felixfbecker/php-advanced-json-rpc/zipball/b5f37dbff9a8ad360ca341f3240dc1c168b45447",
"reference": "b5f37dbff9a8ad360ca341f3240dc1c168b45447",
"shasum": ""
},
"require": {
"netresearch/jsonmapper": "^1.0 || ^2.0",
"netresearch/jsonmapper": "^1.0 || ^2.0 || ^3.0 || ^4.0",
"php": "^7.1 || ^8.0",
"phpdocumentor/reflection-docblock": "^4.3.4 || ^5.0.0"
},
@ -3022,9 +3002,9 @@
"description": "A more advanced JSONRPC implementation",
"support": {
"issues": "https://github.com/felixfbecker/php-advanced-json-rpc/issues",
"source": "https://github.com/felixfbecker/php-advanced-json-rpc/tree/v3.2.0"
"source": "https://github.com/felixfbecker/php-advanced-json-rpc/tree/v3.2.1"
},
"time": "2021-01-10T17:48:47+00:00"
"time": "2021-06-11T22:34:44+00:00"
},
{
"name": "felixfbecker/language-server-protocol",
@ -3273,16 +3253,16 @@
},
{
"name": "netresearch/jsonmapper",
"version": "v2.1.0",
"version": "v4.0.0",
"source": {
"type": "git",
"url": "https://github.com/cweiske/jsonmapper.git",
"reference": "e0f1e33a71587aca81be5cffbb9746510e1fe04e"
"reference": "8bbc021a8edb2e4a7ea2f8ad4fa9ec9dce2fcb8d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/cweiske/jsonmapper/zipball/e0f1e33a71587aca81be5cffbb9746510e1fe04e",
"reference": "e0f1e33a71587aca81be5cffbb9746510e1fe04e",
"url": "https://api.github.com/repos/cweiske/jsonmapper/zipball/8bbc021a8edb2e4a7ea2f8ad4fa9ec9dce2fcb8d",
"reference": "8bbc021a8edb2e4a7ea2f8ad4fa9ec9dce2fcb8d",
"shasum": ""
},
"require": {
@ -3290,10 +3270,10 @@
"ext-pcre": "*",
"ext-reflection": "*",
"ext-spl": "*",
"php": ">=5.6"
"php": ">=7.1"
},
"require-dev": {
"phpunit/phpunit": "~4.8.35 || ~5.7 || ~6.4 || ~7.0",
"phpunit/phpunit": "~7.5 || ~8.0 || ~9.0",
"squizlabs/php_codesniffer": "~3.5"
},
"type": "library",
@ -3318,9 +3298,9 @@
"support": {
"email": "cweiske@cweiske.de",
"issues": "https://github.com/cweiske/jsonmapper/issues",
"source": "https://github.com/cweiske/jsonmapper/tree/master"
"source": "https://github.com/cweiske/jsonmapper/tree/v4.0.0"
},
"time": "2020-04-16T18:48:43+00:00"
"time": "2020-12-01T19:48:11+00:00"
},
{
"name": "nikic/php-parser",
@ -6190,7 +6170,10 @@
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"stability-flags": {
"utopia-php/abuse": 20,
"utopia-php/audit": 20
},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {

View file

@ -430,10 +430,13 @@ services:
- appwrite-influxdb:/var/lib/influxdb:rw
telegraf:
image: appwrite/telegraf:1.1.0
image: appwrite/telegraf:1.2.0
container_name: appwrite-telegraf
networks:
- appwrite
environment:
- _APP_INFLUXDB_HOST
- _APP_INFLUXDB_PORT
# Dev Tools Start ------------------------------------------------------------------------------------------
#
@ -473,6 +476,17 @@ services:
networks:
- appwrite
swagger-validator:
image: 'swaggerapi/swagger-validator-v2:v2.0.5'
container_name: appwrite-swagger-validator
ports:
- '9506:8080'
environment:
- REJECT_LOCAL=false
- REJECT_REDIRECT=false
networks:
- appwrite
# redis-commander:
# image: rediscommander/redis-commander:latest
# restart: unless-stopped

View file

@ -0,0 +1 @@
# Change Log

View file

@ -0,0 +1,94 @@
## Getting Started
### Add your Android Platform
To initialize your SDK and start interacting with Appwrite services, you need to add a new Android platform to your project. To add a new platform, go to your Appwrite console, select your project (create one if you haven't already), and click the 'Add Platform' button on the project Dashboard.
From the options, choose to add a new **Android** platform and add your app credentials.
Add your app <u>name</u> and <u>package name</u>. Your package name is generally the applicationId in your app-level `build.gradle` file. By registering a new platform, you are allowing your app to communicate with the Appwrite API.
### Registering additional activities
In order to capture the Appwrite OAuth callback url, the following activity needs to be added to your [AndroidManifest.xml](https://github.com/appwrite/playground-for-android/blob/master/app/src/main/AndroidManifest.xml). Be sure to replace the **[PROJECT_ID]** string with your actual Appwrite project ID. You can find your Appwrite project ID in your project settings screen in the console.
```xml
<manifest>
<application>
<activity android:name="io.appwrite.views.CallbackActivity" >
<intent-filter android:label="android_web_auth">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="appwrite-callback-[PROJECT_ID]" />
</intent-filter>
</activity>
</application>
</manifest>
```
### Init your SDK
<p>Initialize your SDK with your Appwrite server API endpoint and project ID, which can be found in your project settings page.
```kotlin
import io.appwrite.Client
import io.appwrite.services.Account
val client = Client(context)
.setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
.setProject("5df5acd0d48c2") // Your project ID
.setSelfSigned(true) // Remove in production
```
Before starting to send any API calls to your new Appwrite instance, make sure your Android emulators has network access to the Appwrite server hostname or IP address.
When trying to connect to Appwrite from an emulator or a mobile device, localhost is the hostname of the device or emulator and not your local Appwrite instance. You should replace localhost with your private IP. You can also use a service like [ngrok](https://ngrok.com/) to proxy the Appwrite API.
### Make Your First Request
<p>Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```kotlin
// Register User
val account = Account(client)
val response = account.create(
"email@example.com",
"password"
)
```
### Full Example
```kotlin
import io.appwrite.Client
import io.appwrite.services.Account
val client = Client(context)
.setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
.setProject("5df5acd0d48c2") // Your project ID
.setSelfSigned(true) // Remove in production
val account = Account(client)
val response = account.create(
"email@example.com",
"password"
)
```
### Error Handling
The Appwrite Android SDK raises an `AppwriteException` object with `message`, `code` and `response` properties. You can handle any errors by catching `AppwriteException` and present the `message` to the user or handle it yourself based on the provided error information. Below is an example.
```kotlin
try {
var response = account.create("email@example.com", "password")
Log.d("Appwrite response", response.body?.string())
} catch(e : AppwriteException) {
Log.e("AppwriteException",e.message.toString())
}
```
### Learn more
You can use following resources to learn more and get help
- 🚀 [Getting Started Tutorial](https://appwrite.io/docs/getting-started-for-android)
- 📜 [Appwrite Docs](https://appwrite.io/docs)
- 💬 [Discord Community](https://appwrite.io/discord)
- 🚂 [Appwrite Android Playground](https://github.com/appwrite/playground-for-android)

View file

@ -1,7 +1,7 @@
## Getting Started
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
```typescript
let client = new sdk.Client();
@ -17,7 +17,7 @@ client
### Make your first request
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```typescript
let users = new sdk.Users(client);

View file

@ -23,7 +23,7 @@ The Appwrite SDK uses ASWebAuthenticationSession on iOS 12+ and SFAuthentication
4. In Deployment Info, 'Target' select iOS 11.0
### Android
In order to capture the Appwrite OAuth callback url, the following activity needs to be added to your [AndroidManifest.xml](https://github.com/appwrite/playground-for-flutter/blob/master/android/app/src/main/AndroidManifest.xml). Be sure to relpace the **[PROJECT_ID]** string with your actual Appwrite project ID. You can find your Appwrite project ID in you project settings screen in your Appwrite console.
In order to capture the Appwrite OAuth callback url, the following activity needs to be added to your [AndroidManifest.xml](https://github.com/appwrite/playground-for-flutter/blob/master/android/app/src/main/AndroidManifest.xml). Be sure to replace the **[PROJECT_ID]** string with your actual Appwrite project ID. You can find your Appwrite project ID in your project settings screen in the console.
```xml
<manifest>
@ -48,7 +48,7 @@ While running Flutter Web, make sure your Appwrite server and your Flutter clien
### Init your SDK
<p>Initialize your SDK code with your project ID, which can be found in your project settings page.
<p>Initialize your SDK with your Appwrite server API endpoint and project ID, which can be found in your project settings page.
```dart
import 'package:appwrite/appwrite.dart';
@ -68,7 +68,7 @@ When trying to connect to Appwrite from an emulator or a mobile device, localhos
### Make Your First Request
<p>Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
<p>Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```dart
// Register User

View file

@ -1,7 +1,7 @@
## Getting Started
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page and your new API secret Key project API keys section.
Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page and your new API secret Key project API keys section.
```js
const sdk = require('node-appwrite');
@ -17,7 +17,7 @@ client
```
### Make Your First Request
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```js
let users = new sdk.Users(client);

View file

@ -1,7 +1,7 @@
## Getting Started
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
```php
$client = new Client();
@ -15,7 +15,7 @@ $client
```
### Make Your First Request
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```php
$users = new Users($client);

View file

@ -1,7 +1,7 @@
## Getting Started
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
```python
from appwrite.client import Client
@ -18,7 +18,7 @@ client = Client()
```
### Make Your First Request
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```python
users = Users(client)

View file

@ -1,7 +1,7 @@
## Getting Started
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page and your new API secret Key from project's API keys section.
```ruby
require 'appwrite'
@ -17,7 +17,7 @@ client
```
### Make Your First Request
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
Once your SDK object is set, create any of the Appwrite service objects and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```ruby
users = Appwrite::Users.new(client);

View file

@ -6,7 +6,7 @@ For you to init your SDK and interact with Appwrite services you need to add a w
From the options, choose to add a **Web** platform and add your client app hostname. By adding your hostname to your project platform you are allowing cross-domain communication between your project and the Appwrite API.
### Init your SDK
Initialize your SDK code with your project ID which can be found in your project settings page.
Initialize your SDK with your Appwrite server API endpoint and project ID which can be found in your project settings page.
```js
// Init your Web SDK
@ -19,7 +19,7 @@ sdk
```
### Make Your First Request
Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the API References section.
Once your SDK object is set, access any of the Appwrite services and choose any request to send. Full documentation for any service method you would like to use can be found in your SDK documentation or in the [API References](https://appwrite.io/docs) section.
```js
// Register User

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View file

@ -13,6 +13,9 @@ class Origin extends Validator
const CLIENT_TYPE_FLUTTER_MACOS = 'flutter-macos';
const CLIENT_TYPE_FLUTTER_WINDOWS = 'flutter-windows';
const CLIENT_TYPE_FLUTTER_LINUX = 'flutter-linux';
const CLIENT_TYPE_ANDROID = 'android';
const CLIENT_TYPE_IOS = 'ios';
const SCHEME_TYPE_HTTP = 'http';
const SCHEME_TYPE_HTTPS = 'https';
@ -69,6 +72,8 @@ class Origin extends Validator
case self::CLIENT_TYPE_FLUTTER_MACOS:
case self::CLIENT_TYPE_FLUTTER_WINDOWS:
case self::CLIENT_TYPE_FLUTTER_LINUX:
case self::CLIENT_TYPE_ANDROID:
case self::CLIENT_TYPE_IOS:
$this->clients[] = (isset($platform['key'])) ? $platform['key'] : '';
break;
@ -90,7 +95,7 @@ class Origin extends Validator
}
/**
* Check if Origin has been whiltlisted
* Check if Origin has been allowed
* for access to the API
*
* @param mixed $origin

View file

@ -0,0 +1,29 @@
<?php
namespace Appwrite\Resque;
abstract class Worker
{
public $args = [];
abstract public function init(): void;
abstract public function run(): void;
abstract public function shutdown(): void;
public function setUp(): void
{
$this->init();
}
public function perform()
{
$this->run();
}
public function tearDown(): void
{
$this->shutdown();
}
}

View file

@ -55,6 +55,8 @@ class V07 extends Filter {
case Response::MODEL_ANY:
case Response::MODEL_PREFERENCES: /** ANY was replaced by PREFERENCES in 0.8.x but this is backward compatible with 0.7.x */
case Response::MODEL_NONE:
case Response::MODEL_ERROR:
case Response::MODEL_ERROR_DEV:
$parsedResponse = $content;
break;
default:

View file

@ -96,7 +96,7 @@ class HTTPTest extends Scope
public function testSpecSwagger2()
{
$response = $this->client->call(Client::METHOD_GET, '/specs/swagger2?platform=client', [
$response = $this->client->call(Client::METHOD_GET, '/specs/swagger2?platform=console', [
'content-type' => 'application/json',
], []);
@ -105,11 +105,13 @@ class HTTPTest extends Scope
}
$client = new Client();
$client->setEndpoint('https://validator.swagger.io');
$client->setEndpoint('http://appwrite-swagger-validator:8080');
/**
* Test for SUCCESS
*/
http://localhost:9506/validator?url=http://petstore.swagger.io/v2/swagger.json
$response = $client->call(Client::METHOD_POST, '/validator/debug', [
'content-type' => 'application/json',
], json_decode(file_get_contents(realpath(__DIR__ . '/../../resources/swagger2.json')), true));
@ -124,7 +126,7 @@ class HTTPTest extends Scope
public function testSpecOpenAPI3()
{
$response = $this->client->call(Client::METHOD_GET, '/specs/open-api3?platform=client', [
$response = $this->client->call(Client::METHOD_GET, '/specs/open-api3?platform=console', [
'content-type' => 'application/json',
], []);
@ -133,7 +135,7 @@ class HTTPTest extends Scope
}
$client = new Client();
$client->setEndpoint('https://validator.swagger.io');
$client->setEndpoint('http://appwrite-swagger-validator:8080');
/**
* Test for SUCCESS

File diff suppressed because one or more lines are too long