1
0
Fork 0
mirror of synced 2024-06-29 03:30:34 +12:00

Merge branch 'feat-265-realtime' of https://github.com/appwrite/appwrite into feat-265-realtime-usage

This commit is contained in:
Torsten Dittmann 2021-06-14 20:21:42 +02:00
commit 66ecf9498a
52 changed files with 834 additions and 607 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

@ -56,13 +56,13 @@
.main {
background: {{bg-content}};
border-radius: 3px;
border-radius: 10px;
width: 100%;
}
.wrapper {
box-sizing: border-box;
padding: 20px;
padding: 30px 30px 15px 30px;
}
.content-block {
@ -97,16 +97,15 @@
.btn table td {
background-color: {{bg-content}};
border-radius: 5px;
border-radius: 20px;
text-align: center;
}
.btn a {
background-color: {{bg-content}};
border: solid 1px {{bg-cta}};
border-radius: 5px;
border-radius: 20px;
box-sizing: border-box;
color: #3498db;
color: #577590;
cursor: pointer;
display: inline-block;
font-size: 14px;
@ -123,45 +122,17 @@
.btn-primary a {
background-color: {{bg-cta}};
border-color: {{bg-cta}};
color: {{text-cta}};
}
@media only screen and (max-width: 620px) {
table[class=body] h1 {
font-size: 28px !important;
margin-bottom: 10px !important;
.container {
padding: 0;
width: 100%;
}
table[class=body] p {
font-size: 16px !important;
}
table[class=body] .wrapper {
padding: 10px !important;
}
table[class=body] .content {
padding: 0 !important;
}
table[class=body] .container {
padding: 0 !important;
width: 100% !important;
}
table[class=body] .main {
border-left-width: 0 !important;
border-radius: 0 !important;
border-right-width: 0 !important;
}
table[class=body] .btn table {
width: 100% !important;
}
table[class=body] .btn a {
width: 100% !important;
.btn-primary a {
font-size: 13px;
}
}
@ -198,12 +169,11 @@
}
.btn-primary table td:hover {
background-color: {{bg-cta-hover}} !important;
opacity: 0.7 !important;
}
.btn-primary a:hover {
background-color: {{bg-cta-hover}} !important;
border-color: {{bg-cta-hover}} !important;
opacity: 0.7 !important;
}
}
</style>
@ -220,15 +190,17 @@
<td class="wrapper">
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
{{content}}
</td>
<td>{{content}}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<!-- <div style="text-align: center; line-height: 25px; margin: 15px 0; font-size: 12px; color: #40404c;">
<a href="https://appwrite.io" style="text-decoration: none; color: #40404c;">Powered by <img src="https://appwrite.io/images/appwrite-footer-light.svg" height="15" style="margin: -3px 0" /></a>
</div> -->
</td>
<td>&nbsp;</td>
</tr>

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

@ -1466,17 +1466,16 @@ App::post('/v1/account/recovery')
$cta = new Template(__DIR__.'/../../config/locale/templates/email-cta.tpl');
$body
->setParam('{{content}}', $content->render())
->setParam('{{content}}', $content->render(false))
->setParam('{{cta}}', $cta->render())
->setParam('{{title}}', $locale->getText('account.emails.recovery.title'))
->setParam('{{direction}}', $locale->getText('settings.direction'))
->setParam('{{project}}', $project->getAttribute('name', ['[APP-NAME]']))
->setParam('{{name}}', $profile->getAttribute('name'))
->setParam('{{redirect}}', $url)
->setParam('{{bg-body}}', '#f6f6f6')
->setParam('{{bg-body}}', '#f7f7f7')
->setParam('{{bg-content}}', '#ffffff')
->setParam('{{bg-cta}}', '#3498db')
->setParam('{{bg-cta-hover}}', '#34495e')
->setParam('{{bg-cta}}', '#073b4c')
->setParam('{{text-content}}', '#000000')
->setParam('{{text-cta}}', '#ffffff')
;
@ -1669,17 +1668,16 @@ App::post('/v1/account/verification')
$cta = new Template(__DIR__.'/../../config/locale/templates/email-cta.tpl');
$body
->setParam('{{content}}', $content->render())
->setParam('{{content}}', $content->render(false))
->setParam('{{cta}}', $cta->render())
->setParam('{{title}}', $locale->getText('account.emails.verification.title'))
->setParam('{{direction}}', $locale->getText('settings.direction'))
->setParam('{{project}}', $project->getAttribute('name', ['[APP-NAME]']))
->setParam('{{name}}', $user->getAttribute('name'))
->setParam('{{redirect}}', $url)
->setParam('{{bg-body}}', '#f6f6f6')
->setParam('{{bg-body}}', '#f7f7f7')
->setParam('{{bg-content}}', '#ffffff')
->setParam('{{bg-cta}}', '#3498db')
->setParam('{{bg-cta-hover}}', '#34495e')
->setParam('{{bg-cta}}', '#073b4c')
->setParam('{{text-content}}', '#000000')
->setParam('{{text-cta}}', '#ffffff')
;

View file

@ -267,7 +267,7 @@ App::get('/v1/health/anti-virus')
'status' => (@$antiVirus->ping()) ? 'online' : 'offline',
'version' => @$antiVirus->version(),
]);
} catch( RuntimeException $e) {
} catch( \Exception $e) {
$response->json([
'status' => 'offline',
'version' => '',

View file

@ -242,6 +242,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)
@ -254,7 +255,7 @@ App::get('/v1/storage/files/:fileId/preview')
->inject('response')
->inject('project')
->inject('projectDB')
->action(function ($fileId, $width, $height, $quality, $borderWidth, $borderColor, $borderRadius, $opacity, $rotation, $background, $output, $request, $response, $project, $projectDB) {
->action(function ($fileId, $width, $height, $gravity, $quality, $borderWidth, $borderColor, $borderRadius, $opacity, $rotation, $background, $output, $request, $response, $project, $projectDB) {
/** @var Utopia\Swoole\Request $request */
/** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Document $project */
@ -342,7 +343,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

@ -434,7 +434,7 @@ App::post('/v1/teams/:teamId/memberships')
$title = \sprintf($locale->getText('account.emails.invitation.title'), $team->getAttribute('name', '[TEAM-NAME]'), $project->getAttribute('name', ['[APP-NAME]']));
$body
->setParam('{{content}}', $content->render())
->setParam('{{content}}', $content->render(false))
->setParam('{{cta}}', $cta->render())
->setParam('{{title}}', $title)
->setParam('{{direction}}', $locale->getText('settings.direction'))
@ -442,10 +442,9 @@ App::post('/v1/teams/:teamId/memberships')
->setParam('{{team}}', $team->getAttribute('name', '[TEAM-NAME]'))
->setParam('{{owner}}', $user->getAttribute('name', ''))
->setParam('{{redirect}}', $url)
->setParam('{{bg-body}}', '#f6f6f6')
->setParam('{{bg-body}}', '#f7f7f7')
->setParam('{{bg-content}}', '#ffffff')
->setParam('{{bg-cta}}', '#3498db')
->setParam('{{bg-cta-hover}}', '#34495e')
->setParam('{{bg-cta}}', '#073b4c')
->setParam('{{text-content}}', '#000000')
->setParam('{{text-cta}}', '#ffffff')
;

View file

@ -8,6 +8,7 @@ use Utopia\Validator\WhiteList;
use Appwrite\Network\Validator\Email;
use Utopia\Validator\Text;
use Utopia\Validator\Range;
use Utopia\Validator\Boolean;
use Utopia\Audit\Audit;
use Utopia\Audit\Adapters\MySQL as AuditAdapter;
use Appwrite\Auth\Auth;
@ -369,6 +370,43 @@ App::patch('/v1/users/:userId/status')
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/verification')
->desc('Update Email Verification')
->groups(['api', 'users'])
->label('event', 'users.update.verification')
->label('scope', 'users.write')
->label('sdk.auth', [APP_AUTH_TYPE_KEY])
->label('sdk.namespace', 'users')
->label('sdk.method', 'updateVerification')
->label('sdk.description', '/docs/references/users/update-user-verification.md')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_USER)
->param('userId', '', new UID(), 'User unique ID.')
->param('emailVerification', false, new Boolean(), 'User Email Verification Status.')
->inject('response')
->inject('projectDB')
->action(function ($userId, $emailVerification, $response, $projectDB) {
/** @var Appwrite\Utopia\Response $response */
/** @var Appwrite\Database\Database $projectDB */
$user = $projectDB->getDocument($userId);
if (empty($user->getId()) || Database::SYSTEM_COLLECTION_USERS != $user->getCollection()) {
throw new Exception('User not found', 404);
}
$user = $projectDB->updateDocument(\array_merge($user->getArrayCopy(), [
'emailVerification' => $emailVerification,
]));
if (false === $user) {
throw new Exception('Failed saving user to DB', 500);
}
$response->dynamic($user, Response::MODEL_USER);
});
App::patch('/v1/users/:userId/prefs')
->desc('Update User Preferences')
->groups(['api', 'users'])

View file

@ -12,26 +12,6 @@ use Swoole\Http\Request as SwooleRequest;
use Swoole\Http\Response as SwooleResponse;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Domains\Domain;
// xdebug_start_trace('/tmp/trace');
Files::load(__DIR__ . '/../public');
include __DIR__ . '/controllers/general.php';
$domain = App::getEnv('_APP_DOMAIN', '');
Console::info('Issuing a TLS certificate for the master domain ('.$domain.') in 30 seconds.
Make sure your domain points to your server IP or restart your Appwrite server to try again.'); // TODO move this to installation script
ResqueScheduler::enqueueAt(\time() + 30, 'v1-certificates', 'CertificatesV1', [
'document' => [],
'domain' => $domain,
'validateTarget' => false,
'validateCNAME' => false,
]);
$http = new Server("0.0.0.0", App::getEnv('PORT', 80));
@ -101,8 +81,8 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo
$register->set('db', function () use (&$db) {
return $db;
});
$register->set('cache', function () use (&$redis) { // Register cache connection
$register->set('cache', function () use (&$redis) {
return $redis;
});

View file

@ -161,19 +161,21 @@ $register->set('dbPool', function () { // Register DB connection
return $pool;
});
$register->set('redisPool', function () {
$user = App::getEnv('_APP_REDIS_USER', '');
$pass = App::getEnv('_APP_REDIS_PASS', '');
$auth = [];
if ($user) {
$auth[] = $user;
$redisHost = App::getEnv('_APP_REDIS_HOST', '');
$redisPort = App::getEnv('_APP_REDIS_PORT', '');
$redisUser = App::getEnv('_APP_REDIS_USER', '');
$redisPass = App::getEnv('_APP_REDIS_PASS', '');
$redisAuth = [];
if ($redisUser) {
$redisAuth[] = $redisUser;
}
if ($pass) {
$auth[] = $pass;
if ($redisPass) {
$redisAuth[] = $redisPass;
}
$pool = new RedisPool(10, App::getEnv('_APP_REDIS_HOST', ''), App::getEnv('_APP_REDIS_PORT', ''), $auth);
$pool = new RedisPool(10, $redisHost, $redisPort, $redisAuth);
return $pool;
});

View file

@ -1,336 +1,13 @@
<?php
use Appwrite\Realtime\Server;
require_once __DIR__ . '/init.php';
use Appwrite\Database\Pool\PDOPool;
use Appwrite\Database\Pool\RedisPool;
use Appwrite\Event\Event;
use Appwrite\Network\Validator\Origin;
use Appwrite\Realtime\Realtime;
use Appwrite\Utopia\Response;
use Swoole\Http\Request;
use Swoole\Http\Response as SwooleResponse;
use Swoole\Process;
use Swoole\Table;
use Swoole\Timer;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Swoole\Request as SwooleRequest;
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
/**
* TODO List
*
* - JWT Authentication (in path / or in message)
*
* Protocols Support:
* - Websocket support: https://www.swoole.co.uk/docs/modules/swoole-websocket-server
*/
Swoole\Runtime::enableCoroutine(SWOOLE_HOOK_ALL);
$server = new Server('0.0.0.0', 80, SWOOLE_PROCESS);
$server->set([
$config = [
'package_max_length' => 64000 // Default maximum Package Size (64kb)
]);
];
$subscriptions = [];
$connections = [];
$stats = new Table(4096, 1);
$stats->column('projectId', Table::TYPE_STRING, 64);
$stats->column('connections', Table::TYPE_INT);
$stats->column('connectionsTotal', Table::TYPE_INT);
$stats->column('messages', Table::TYPE_INT);
$stats->create();
/**
* Sends usage stats every 10 seconds.
*/
Timer::tick(10000, function () use (&$stats) {
/** @var Table $stats */
foreach ($stats as $projectId => $value) {
if (empty($value['connections']) && empty($value['messages'])) {
continue;
}
$connections = $value['connections'];
$messages = $value['messages'];
$usage = new Event('v1-usage', 'UsageV1');
$usage
->setParam('projectId', $projectId)
->setParam('realtimeConnections', $connections)
->setParam('realtimeMessages', $messages)
->setParam('networkRequestSize', 0)
->setParam('networkResponseSize', 0);
$stats->set($projectId, [
'projectId' => $projectId,
'messages' => 0,
'connections' => 0
]);
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$usage->trigger();
}
}
});
$server->on('workerStart', function ($server, $workerId) use (&$subscriptions, &$register, &$stats) {
Console::success('Worker ' . $workerId . ' started succefully');
$attempts = 0;
$start = time();
$redisPool = $register->get('redisPool');
/**
* Sending current connections to project channels on the console project every 5 seconds.
*/
$server->tick(5000, function () use (&$server, &$subscriptions, &$stats) {
if (
array_key_exists('console', $subscriptions)
&& array_key_exists('role:member', $subscriptions['console'])
&& array_key_exists('project', $subscriptions['console']['role:member'])
) {
$payload = [];
foreach ($stats as $projectId => $value) {
$payload[$projectId] = $value['connectionsTotal'];
}
foreach ($subscriptions['console']['role:member']['project'] as $connection => $value) {
$server->push(
$connection,
json_encode([
'event' => 'stats.connections',
'channels' => ['project'],
'timestamp' => time(),
'payload' => $payload
]),
SWOOLE_WEBSOCKET_OPCODE_TEXT,
SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
);
}
}
});
while ($attempts < 300) {
try {
if ($attempts > 0) {
Console::error('Pub/sub connection lost (lasted ' . (time() - $start) . ' seconds, worker: ' . $workerId . ').
Attempting restart in 5 seconds (attempt #' . $attempts . ')');
sleep(5); // 5 sec delay between connection attempts
}
/** @var Swoole\Coroutine\Redis $redis */
$redis = $redisPool->get();
if ($redis->ping(true)) {
$attempts = 0;
Console::success('Pub/sub connection established (worker: ' . $workerId . ')');
} else {
Console::error('Pub/sub failed (worker: ' . $workerId . ')');
}
$redis->subscribe(['realtime'], function ($redis, $channel, $payload) use ($server, $workerId, &$subscriptions, &$stats) {
/**
* Supported Resources:
* - Collection
* - Document
* - File
* - Account
* - Session
* - Team? (not implemented yet)
* - Membership? (not implemented yet)
* - Function
* - Execution
*/
$event = json_decode($payload, true);
$receivers = Realtime::identifyReceivers($event, $subscriptions);
// Temporarily print debug logs by default for Alpha testing.
// if (App::isDevelopment() && !empty($receivers)) {
if (!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);
}
foreach ($receivers as $receiver) {
if ($server->exist($receiver) && $server->isEstablished($receiver)) {
$server->push(
$receiver,
json_encode($event['data']),
SWOOLE_WEBSOCKET_OPCODE_TEXT,
SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
);
} else {
$server->close($receiver);
}
}
if (($num = count($receivers)) > 0) {
$stats->incr($event['project'], 'messages', $num);
}
});
} catch (\Throwable $th) {
Console::error('Pub/sub error: ' . $th->getMessage());
$redisPool->put($redis);
$attempts++;
continue;
}
$attempts++;
}
Console::error('Failed to restart pub/sub...');
});
$server->on('start', function (Server $server) {
Console::success('Server started succefully');
Console::info("Master pid {$server->master_pid}, manager pid {$server->manager_pid}");
// listen ctrl + c
Process::signal(2, function () use ($server) {
Console::log('Stop by Ctrl+C');
$server->shutdown();
});
});
$server->on('open', function (Server $server, Request $request) use (&$connections, &$subscriptions, &$register, &$stats) {
$app = new App('UTC');
$connection = $request->fd;
$request = new SwooleRequest($request);
$db = $register->get('dbPool')->get();
$redis = $register->get('redisPool')->get();
$register->set('db', function () use (&$db) {
return $db;
});
$register->set('cache', function () use (&$redis) { // Register cache connection
return $redis;
});
Console::info("Connection open (user: {$connection}, worker: {$server->getWorkerId()})");
App::setResource('request', function () use ($request) {
return $request;
});
App::setResource('response', function () {
return new Response(new SwooleResponse());
});
try {
/** @var Appwrite\Database\Document $user */
$user = $app->getResource('user');
/** @var Appwrite\Database\Document $project */
$project = $app->getResource('project');
/** @var Appwrite\Database\Document $console */
$console = $app->getResource('console');
/*
* Project Check
*/
if (empty($project->getId())) {
throw new Exception('Missing or unknown project ID', 1008);
}
/*
* Abuse Check
*
* Abuse limits are connecting 128 times per minute and ip address.
*/
$timeLimit = new TimeLimit('url:{url},ip:{ip}', 128, 60, function () use ($db) {
return $db;
});
$timeLimit
->setNamespace('app_' . $project->getId())
->setParam('{ip}', $request->getIP())
->setParam('{url}', $request->getURI());
$abuse = new Abuse($timeLimit);
if ($abuse->check() && App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled') {
throw new Exception('Too many requests', 1013);
}
/*
* 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();
$originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', [])));
if (!$originValidator->isValid($origin) && $project->getId() !== 'console') {
throw new Exception($originValidator->getDescription(), 1008);
}
Realtime::setUser($user);
$roles = Realtime::getRoles();
$channels = Realtime::parseChannels($request->getQuery('channels', []));
/**
* Channels Check
*/
if (empty($channels)) {
throw new Exception('Missing channels', 1008);
}
Realtime::subscribe($project->getId(), $connection, $roles, $subscriptions, $connections, $channels);
$server->push($connection, json_encode($channels));
$stats->incr($project->getId(), 'connections');
$stats->incr($project->getId(), 'connectionsTotal');
} catch (\Throwable $th) {
$response = [
'code' => $th->getCode(),
'message' => $th->getMessage()
];
// Temporarily print debug logs by default for Alpha testing.
//if (App::isDevelopment()) {
Console::error("[Error] Connection Error");
Console::error("[Error] Code: " . $response['code']);
Console::error("[Error] Message: " . $response['message']);
//}
$server->push($connection, json_encode($response));
$server->close($connection);
}
/**
* Put used PDO and Redis Connections back into their pools.
*/
/** @var PDOPool $dbPool */
$dbPool = $register->get('dbPool');
$dbPool->put($db);
/** @var RedisPool $redisPool */
$redisPool = $register->get('redisPool');
$redisPool->put($redis);
});
$server->on('message', function (Server $server, Frame $frame) {
$server->push($frame->fd, 'Sending messages is not allowed.');
$server->close($frame->fd);
});
$server->on('close', function (Server $server, int $connection) use (&$connections, &$subscriptions, &$stats) {
if (array_key_exists($connection, $connections)) {
$stats->decr($connections[$connection]['projectId'], 'connectionsTotal');
}
Realtime::unsubscribe($connection, $subscriptions, $connections);
Console::info('Connection close: ' . $connection);
});
$server->start();
$realtimeServer = new Server($register, config: $config);

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

@ -417,11 +417,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

@ -8,7 +8,6 @@ use Utopia\CLI\Console;
require_once __DIR__.'/../workers.php';
Console::title('Audits V1 Worker');
Console::success(APP_NAME.' audits worker v1 has started');
class AuditsV1 extends Worker
@ -44,4 +43,4 @@ class AuditsV1 extends Worker
{
// ... Remove environment for this job
}
}
}

View file

@ -1,20 +1,19 @@
<?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__.'/../workers.php';
Console::title('Certificates V1 Worker');
Console::success(APP_NAME.' certificates worker v1 has started');
class CertificatesV1 extends Worker
@ -208,4 +207,4 @@ class CertificatesV1 extends Worker
public function shutdown(): void
{
}
}
}

View file

@ -17,7 +17,6 @@ use Utopia\Audit\Adapters\MySQL as AuditAdapter;
require_once __DIR__.'/../workers.php';
Console::title('Deletes V1 Worker');
Console::success(APP_NAME.' deletes worker v1 has started'."\n");
class DeletesV1 extends Worker

View file

@ -578,4 +578,4 @@ class FunctionsV1 extends Worker
public function shutdown(): void
{
}
}
}

View file

@ -7,7 +7,6 @@ use Utopia\CLI\Console;
require_once __DIR__.'/../workers.php';
Console::title('Mails V1 Worker');
Console::success(APP_NAME.' mails worker v1 has started'."\n");
class MailsV1 extends Worker
@ -72,4 +71,4 @@ class MailsV1 extends Worker
public function shutdown(): void
{
}
}
}

View file

@ -1,19 +1,18 @@
<?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__.'/../workers.php';
Console::title('Tasks V1 Worker');
Console::success(APP_NAME.' tasks worker v1 has started');
class TasksV1 extends Worker
@ -209,4 +208,4 @@ class TasksV1 extends Worker
public function shutdown(): void
{
}
}
}

View file

@ -7,7 +7,6 @@ use Utopia\CLI\Console;
require_once __DIR__.'/../workers.php';
Console::title('Usage V1 Worker');
Console::success(APP_NAME.' usage worker v1 has started');
class UsageV1 extends Worker
@ -80,4 +79,4 @@ class UsageV1 extends Worker
public function shutdown(): void
{
}
}
}

View file

@ -1,12 +1,12 @@
<?php
use Appwrite\Resque\Worker;
use Utopia\App;
use Utopia\CLI\Console;
require_once __DIR__.'/../workers.php';
Console::title('Webhooks V1 Worker');
Console::success(APP_NAME.' webhooks worker v1 has started');
use Appwrite\Resque\Worker;
@ -92,4 +92,4 @@ class WebhooksV1 extends Worker
public function shutdown(): void
{
}
}
}

View file

@ -51,7 +51,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",

56
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": "c73fd7564a192ea65a1398edccb590f4",
"content-hash": "ecfe641507c78e5e886eeece09c01d50",
"packages": [
{
"name": "adhocore/jwt",
@ -1742,16 +1742,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": {
@ -1789,9 +1789,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",
@ -2713,20 +2713,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"
},
@ -2752,9 +2752,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",
@ -3003,16 +3003,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": {
@ -3020,10 +3020,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",
@ -3048,9 +3048,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",
@ -4472,16 +4472,16 @@
},
{
"name": "sebastian/global-state",
"version": "5.0.2",
"version": "5.0.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/global-state.git",
"reference": "a90ccbddffa067b51f574dea6eb25d5680839455"
"reference": "23bd5951f7ff26f12d4e3242864df3e08dec4e49"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/a90ccbddffa067b51f574dea6eb25d5680839455",
"reference": "a90ccbddffa067b51f574dea6eb25d5680839455",
"url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/23bd5951f7ff26f12d4e3242864df3e08dec4e49",
"reference": "23bd5951f7ff26f12d4e3242864df3e08dec4e49",
"shasum": ""
},
"require": {
@ -4524,7 +4524,7 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/global-state/issues",
"source": "https://github.com/sebastianbergmann/global-state/tree/5.0.2"
"source": "https://github.com/sebastianbergmann/global-state/tree/5.0.3"
},
"funding": [
{
@ -4532,7 +4532,7 @@
"type": "github"
}
],
"time": "2020-10-26T15:55:19+00:00"
"time": "2021-06-11T13:31:12+00:00"
},
{
"name": "sebastian/lines-of-code",

View file

@ -481,10 +481,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 ------------------------------------------------------------------------------------------
#

View file

@ -0,0 +1 @@
Update the user email verification status by its unique ID.

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

@ -9,11 +9,11 @@ abstract class Pool
abstract public function get();
public function destruct ()
public function destruct()
{
$this->available = false;
while (!$this->pool->isEmpty()) {
$this->pool->pop();
}
}
}
}

View file

@ -12,12 +12,12 @@ class PDOPool extends Pool
{
$this->pool = new SplQueue;
$this->size = $size;
for ($i=0; $i < $this->size; $i++) {
for ($i = 0; $i < $this->size; $i++) {
$pdo = new PDO(
"mysql:".
"host={$host};".
"dbname={$schema};" .
"charset={$charset}",
"mysql:" .
"host={$host};" .
"dbname={$schema};" .
"charset={$charset}",
$user,
$pass,
[
@ -28,17 +28,17 @@ class PDOPool extends Pool
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
]
);
);
$this->pool->enqueue($pdo);
}
}
public function put (PDO $pdo)
public function put(PDO $pdo)
{
$this->pool->enqueue($pdo);
}
public function get (): PDO
public function get(): PDO
{
if ($this->available && count($this->pool) > 0) {
return $this->pool->dequeue();

View file

@ -13,11 +13,11 @@ class RedisPool extends Pool
{
$this->pool = new SplQueue;
$this->size = $size;
for ($i=0; $i < $this->size; $i++) {
for ($i = 0; $i < $this->size; $i++) {
$redis = new Redis();
$redis->pconnect($host, $port);
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1);
if ($auth) {
$redis->auth($auth);
}
@ -26,12 +26,12 @@ class RedisPool extends Pool
}
}
public function put (Redis $redis)
public function put(Redis $redis)
{
$this->pool->enqueue($redis);
}
public function get (): Redis
public function get(): Redis
{
if ($this->available && !$this->pool->isEmpty()) {
return $this->pool->dequeue();

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

@ -5,7 +5,7 @@ namespace Appwrite\Realtime;
use Appwrite\Auth\Auth;
use Appwrite\Database\Document;
class Realtime
class Parser
{
/**
* @var Document $user

View file

@ -0,0 +1,393 @@
<?php
namespace Appwrite\Realtime;
use Appwrite\Event\Event;
use Appwrite\Network\Validator\Origin;
use Appwrite\Utopia\Response;
use Exception;
use Swoole\Http\Request;
use Swoole\Http\Response as SwooleResponse;
use Swoole\Process;
use Swoole\Table;
use Swoole\Timer;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server as SwooleServer;
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Exception as UtopiaException;
use Utopia\Registry\Registry;
use Utopia\Swoole\Request as SwooleRequest;
class Server
{
private Registry $register;
private SwooleServer $server;
private Table $stats;
private array $subscriptions;
private array $connections;
public function __construct(Registry &$register, $host = '0.0.0.0', $port = 80, $config = [])
{
$this->subscriptions = [];
$this->connections = [];
$this->register = $register;
$this->stats = new Table(4096, 1);
$this->stats->column('projectId', Table::TYPE_STRING, 64);
$this->stats->column('connections', Table::TYPE_INT);
$this->stats->column('connectionsTotal', Table::TYPE_INT);
$this->stats->column('messages', Table::TYPE_INT);
$this->stats->create();
$this->server = new SwooleServer($host, $port, SWOOLE_PROCESS);
$this->server->set($config);
$this->server->on('start', [$this, 'onStart']);
$this->server->on('workerStart', [$this, 'onWorkerStart']);
$this->server->on('open', [$this, 'onOpen']);
$this->server->on('message', [$this, 'onMessage']);
$this->server->on('close', [$this, 'onClose']);
$this->server->start();
}
/**
* This is executed when the Realtime server starts.
* @param SwooleServer $server
* @return void
*/
public function onStart(SwooleServer $server): void
{
Console::success('Server started succefully');
Console::info("Master pid {$server->master_pid}, manager pid {$server->manager_pid}");
Timer::tick(10000, function () {
/** @var Table $stats */
foreach ($this->stats as $projectId => $value) {
if (empty($value['connections']) && empty($value['messages'])) {
continue;
}
$connections = $value['connections'];
$messages = $value['messages'];
$usage = new Event('v1-usage', 'UsageV1');
$usage
->setParam('projectId', $projectId)
->setParam('realtimeConnections', $connections)
->setParam('realtimeMessages', $messages)
->setParam('networkRequestSize', 0)
->setParam('networkResponseSize', 0);
$this->stats->set($projectId, [
'projectId' => $projectId,
'messages' => 0,
'connections' => 0
]);
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$usage->trigger();
}
}
});
Process::signal(2, function () use ($server) {
Console::log('Stop by Ctrl+C');
$server->shutdown();
});
}
/**
* This is executed when a WebSocket worker process starts.
* @param SwooleServer $server
* @param int $workerId
* @return void
* @throws Exception
*/
public function onWorkerStart(SwooleServer $server, int $workerId): void
{
Console::success('Worker ' . $workerId . ' started succefully');
$attempts = 0;
$start = time();
$redisPool = $this->register->get('redisPool');
/**
* Sending current connections to project channels on the console project every 5 seconds.
*/
$server->tick(5000, function () use (&$server) {
$this->tickSendProjectUsage($server);
});
while ($attempts < 300) {
try {
if ($attempts > 0) {
Console::error('Pub/sub connection lost (lasted ' . (time() - $start) . ' seconds, worker: ' . $workerId . ').
Attempting restart in 5 seconds (attempt #' . $attempts . ')');
sleep(5); // 5 sec delay between connection attempts
}
/** @var Swoole\Coroutine\Redis $redis */
$redis = $redisPool->get();
if ($redis->ping(true)) {
$attempts = 0;
Console::success('Pub/sub connection established (worker: ' . $workerId . ')');
} else {
Console::error('Pub/sub failed (worker: ' . $workerId . ')');
}
$redis->subscribe(['realtime'], function ($redis, $channel, $payload) use ($server, $workerId) {
$this->onRedisPublish($payload, $server, $workerId);
});
} catch (\Throwable $th) {
Console::error('Pub/sub error: ' . $th->getMessage());
$redisPool->put($redis);
$attempts++;
continue;
}
$attempts++;
}
Console::error('Failed to restart pub/sub...');
}
/**
* This is executed when a new Realtime connection is established.
* @param SwooleServer $server
* @param Request $request
* @return void
* @throws Exception
* @throws UtopiaException
*/
public function onOpen(SwooleServer $server, Request $request): void
{
$app = new App('UTC');
$connection = $request->fd;
$request = new SwooleRequest($request);
$db = $this->register->get('dbPool')->get();
$redis = $this->register->get('redisPool')->get();
$this->register->set('db', function () use (&$db) {
return $db;
});
$this->register->set('cache', function () use (&$redis) { // Register cache connection
return $redis;
});
Console::info("Connection open (user: {$connection}, worker: {$server->getWorkerId()})");
App::setResource('request', function () use ($request) {
return $request;
});
App::setResource('response', function () {
return new Response(new SwooleResponse());
});
try {
/** @var \Appwrite\Database\Document $user */
$user = $app->getResource('user');
/** @var \Appwrite\Database\Document $project */
$project = $app->getResource('project');
/** @var \Appwrite\Database\Document $console */
$console = $app->getResource('console');
/*
* Project Check
*/
if (empty($project->getId())) {
throw new Exception('Missing or unknown project ID', 1008);
}
/*
* Abuse Check
*
* Abuse limits are connecting 128 times per minute and ip address.
*/
$timeLimit = new TimeLimit('url:{url},ip:{ip}', 128, 60, function () use ($db) {
return $db;
});
$timeLimit
->setNamespace('app_' . $project->getId())
->setParam('{ip}', $request->getIP())
->setParam('{url}', $request->getURI());
$abuse = new Abuse($timeLimit);
if ($abuse->check() && App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') === 'enabled') {
throw new Exception('Too many requests', 1013);
}
/*
* 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();
$originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', [])));
if (!$originValidator->isValid($origin) && $project->getId() !== 'console') {
throw new Exception($originValidator->getDescription(), 1008);
}
Parser::setUser($user);
$roles = Parser::getRoles();
$channels = Parser::parseChannels($request->getQuery('channels', []));
/**
* Channels Check
*/
if (empty($channels)) {
throw new Exception('Missing channels', 1008);
}
Parser::subscribe($project->getId(), $connection, $roles, $this->subscriptions, $this->connections, $channels);
$server->push($connection, json_encode($channels));
$this->stats->incr($project->getId(), 'connections');
$this->stats->incr($project->getId(), 'connectionsTotal');
} catch (\Throwable $th) {
$response = [
'code' => $th->getCode(),
'message' => $th->getMessage()
];
// Temporarily print debug logs by default for Alpha testing.
//if (App::isDevelopment()) {
Console::error("[Error] Connection Error");
Console::error("[Error] Code: " . $response['code']);
Console::error("[Error] Message: " . $response['message']);
//}
$server->push($connection, json_encode($response));
$server->close($connection);
}
/**
* Put used PDO and Redis Connections back into their pools.
*/
/** @var PDOPool $dbPool */
$dbPool = $this->register->get('dbPool');
$dbPool->put($db);
/** @var RedisPool $redisPool */
$redisPool = $this->register->get('redisPool');
$redisPool->put($redis);
}
/**
* This is executed when a message is received by the Realtime server.
* @param SwooleServer $server
* @param Frame $frame
* @return void
*/
public function onMessage(SwooleServer $server, Frame $frame)
{
$server->push($frame->fd, 'Sending messages is not allowed.');
$server->close($frame->fd);
}
/**
* This is executed when a Realtime connection is closed.
* @param SwooleServer $server
* @param int $connection
* @return void
*/
public function onClose(SwooleServer $server, int $connection)
{
if (array_key_exists($connection, $this->connections)) {
$this->stats->decr($this->connections[$connection]['projectId'], 'connectionsTotal');
}
Parser::unsubscribe($connection, $this->subscriptions, $this->connections);
Console::info('Connection close: ' . $connection);
}
/**
* This is executed when an event is published on realtime channel in Redis.
* @param string $payload
* @param SwooleServer $server
* @param int $workerId
* @return void
*/
public function onRedisPublish(string $payload, SwooleServer &$server, int $workerId)
{
/**
* Supported Resources:
* - Collection
* - Document
* - File
* - Account
* - Session
* - Team? (not implemented yet)
* - Membership? (not implemented yet)
* - Function
* - Execution
*/
$event = json_decode($payload, true);
$receivers = Parser::identifyReceivers($event, $this->subscriptions);
// Temporarily print debug logs by default for Alpha testing.
// if (App::isDevelopment() && !empty($receivers)) {
if (!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);
}
foreach ($receivers as $receiver) {
if ($server->exist($receiver) && $server->isEstablished($receiver)) {
$server->push(
$receiver,
json_encode($event['data']),
SWOOLE_WEBSOCKET_OPCODE_TEXT,
SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
);
} else {
$server->close($receiver);
}
}
if (($num = count($receivers)) > 0) {
$this->stats->incr($event['project'], 'messages', $num);
}
}
/**
* This sends the usage to the `console` channel.
* @param SwooleServer $server
* @return void
*/
public function tickSendProjectUsage(SwooleServer &$server)
{
if (
array_key_exists('console', $this->subscriptions)
&& array_key_exists('role:member', $this->subscriptions['console'])
&& array_key_exists('project', $this->subscriptions['console']['role:member'])
) {
$payload = [];
foreach ($this->stats as $projectId => $value) {
$payload[$projectId] = $value['connectionsTotal'];
}
foreach ($this->subscriptions['console']['role:member']['project'] as $connection => $value) {
$server->push(
$connection,
json_encode([
'event' => 'stats.connections',
'channels' => ['project'],
'timestamp' => time(),
'payload' => $payload
]),
SWOOLE_WEBSOCKET_OPCODE_TEXT,
SWOOLE_WEBSOCKET_FLAG_FIN | SWOOLE_WEBSOCKET_FLAG_COMPRESS
);
}
}
}
}

View file

@ -2,18 +2,14 @@
namespace Appwrite\Resque;
use Swoole\Runtime;
use function Swoole\Coroutine\run;
abstract class Worker
{
public $args = [];
abstract public function init(): void;
abstract public function run(): void;
abstract public function shutdown(): void;
public function setUp(): void

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

@ -94,33 +94,33 @@ class HTTPTest extends Scope
$this->assertStringContainsString('# robotstxt.org/', $response['body']);
}
public function testSpecSwagger2()
{
$response = $this->client->call(Client::METHOD_GET, '/specs/swagger2?platform=client', [
'content-type' => 'application/json',
], []);
// public function testSpecSwagger2()
// {
// $response = $this->client->call(Client::METHOD_GET, '/specs/swagger2?platform=client', [
// 'content-type' => 'application/json',
// ], []);
if(!file_put_contents(__DIR__ . '/../../resources/swagger2.json', json_encode($response['body']))) {
throw new Exception('Failed to save spec file');
}
// if(!file_put_contents(__DIR__ . '/../../resources/swagger2.json', json_encode($response['body']))) {
// throw new Exception('Failed to save spec file');
// }
$client = new Client();
$client->setEndpoint('https://validator.swagger.io');
// $client = new Client();
// $client->setEndpoint('https://validator.swagger.io');
/**
* Test for SUCCESS
*/
$response = $client->call(Client::METHOD_POST, '/validator/debug', [
'content-type' => 'application/json',
], json_decode(file_get_contents(realpath(__DIR__ . '/../../resources/swagger2.json')), true));
// /**
// * Test for SUCCESS
// */
// $response = $client->call(Client::METHOD_POST, '/validator/debug', [
// 'content-type' => 'application/json',
// ], json_decode(file_get_contents(realpath(__DIR__ . '/../../resources/swagger2.json')), true));
$response['body'] = json_decode($response['body'], true);
// $response['body'] = json_decode($response['body'], true);
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertTrue(empty($response['body']));
// $this->assertEquals(200, $response['headers']['status-code']);
// $this->assertTrue(empty($response['body']));
unlink(realpath(__DIR__ . '/../../resources/swagger2.json'));
}
// unlink(realpath(__DIR__ . '/../../resources/swagger2.json'));
// }
public function testSpecOpenAPI3()
{
@ -209,4 +209,4 @@ class HTTPTest extends Scope
$this->assertIsString($body['server-ruby']);
$this->assertIsString($body['server-cli']);
}
}
}

View file

@ -122,6 +122,35 @@ trait UsersBase
return $data;
}
/**
* @depends testGetUser
*/
public function testUpdateEmailVerification(array $data):array
{
/**
* Test for SUCCESS
*/
$user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/verification', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'emailVerification' => true,
]);
$this->assertEquals($user['headers']['status-code'], 200);
$this->assertEquals($user['body']['emailVerification'], true);
$user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()));
$this->assertEquals($user['headers']['status-code'], 200);
$this->assertEquals($user['body']['emailVerification'], true);
return $data;
}
/**
* @depends testGetUser
*/

View file

@ -3,7 +3,7 @@
namespace Appwrite\Tests;
use Appwrite\Database\Document;
use Appwrite\Realtime\Realtime;
use Appwrite\Realtime;
use PHPUnit\Framework\TestCase;
class RealtimeChannelsTest extends TestCase
@ -46,7 +46,7 @@ class RealtimeChannelsTest extends TestCase
*/
for ($i = 0; $i < $this->connectionsPerChannel; $i++) {
foreach ($this->allChannels as $index => $channel) {
Realtime::setUser(new Document([
Realtime\Parser::setUser(new Document([
'$id' => 'user' . $this->connectionsCount,
'memberships' => [
[
@ -57,10 +57,10 @@ class RealtimeChannelsTest extends TestCase
]
]
]));
$roles = Realtime::getRoles();
$parsedChannels = Realtime::parseChannels([0 => $channel]);
$roles = Realtime\Parser::getRoles();
$parsedChannels = Realtime\Parser::parseChannels([0 => $channel]);
Realtime::subscribe(
Realtime\Parser::subscribe(
'1',
$this->connectionsCount,
$roles,
@ -78,14 +78,14 @@ class RealtimeChannelsTest extends TestCase
*/
for ($i = 0; $i < $this->connectionsPerChannel; $i++) {
foreach ($this->allChannels as $index => $channel) {
Realtime::setUser(new Document([
Realtime\Parser::setUser(new Document([
'$id' => ''
]));
$roles = Realtime::getRoles();
$parsedChannels = Realtime::parseChannels([0 => $channel]);
$roles = Realtime\Parser::getRoles();
$parsedChannels = Realtime\Parser::parseChannels([0 => $channel]);
Realtime::subscribe(
Realtime\Parser::subscribe(
'1',
$this->connectionsCount,
$roles,
@ -130,13 +130,13 @@ class RealtimeChannelsTest extends TestCase
*/
$this->assertCount($this->connectionsTotal, $this->connections);
Realtime::unsubscribe(-1, $this->subscriptions, $this->connections);
Realtime\Parser::unsubscribe(-1, $this->subscriptions, $this->connections);
$this->assertCount($this->connectionsTotal, $this->connections);
$this->assertCount(($this->connectionsAuthenticated + (3 * $this->connectionsPerChannel) + 2), $this->subscriptions['1']);
for ($i = 0; $i < $this->connectionsCount; $i++) {
Realtime::unsubscribe($i, $this->subscriptions, $this->connections);
Realtime\Parser::unsubscribe($i, $this->subscriptions, $this->connections);
$this->assertCount(($this->connectionsCount - $i - 1), $this->connections);
}
@ -161,7 +161,7 @@ class RealtimeChannelsTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -197,7 +197,7 @@ class RealtimeChannelsTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -234,7 +234,7 @@ class RealtimeChannelsTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -271,7 +271,7 @@ class RealtimeChannelsTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -300,7 +300,7 @@ class RealtimeChannelsTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);

View file

@ -3,7 +3,7 @@
namespace Appwrite\Tests;
use Appwrite\Database\Document;
use Appwrite\Realtime\Realtime;
use Appwrite\Realtime;
use PHPUnit\Framework\TestCase;
class RealtimeGuestTest extends TestCase
@ -13,11 +13,11 @@ class RealtimeGuestTest extends TestCase
public function testGuest()
{
Realtime::setUser(new Document([
Realtime\Parser::setUser(new Document([
'$id' => ''
]));
$roles = Realtime::getRoles();
$roles = Realtime\Parser::getRoles();
$this->assertCount(1, $roles);
$this->assertContains('role:guest', $roles);
@ -29,7 +29,7 @@ class RealtimeGuestTest extends TestCase
4 => 'account.456'
];
$channels = Realtime::parseChannels($channels);
$channels = Realtime\Parser::parseChannels($channels);
$this->assertCount(3, $channels);
$this->assertArrayHasKey('files', $channels);
$this->assertArrayHasKey('documents', $channels);
@ -37,7 +37,7 @@ class RealtimeGuestTest extends TestCase
$this->assertArrayNotHasKey('account', $channels);
$this->assertArrayNotHasKey('account.456', $channels);
Realtime::subscribe('1', 1, $roles, $this->subscriptions, $this->connections, $channels);
Realtime\Parser::subscribe('1', 1, $roles, $this->subscriptions, $this->connections, $channels);
$event = [
'project' => '1',
@ -50,7 +50,7 @@ class RealtimeGuestTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -60,7 +60,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['role:guest'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -70,7 +70,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['role:member'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -79,7 +79,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['user:123'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -88,7 +88,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['team:abc'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -97,7 +97,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['team:abc/administrator'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -106,7 +106,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['team:abc/god'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -115,7 +115,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['team:def'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -124,7 +124,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['team:def/guest'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -133,7 +133,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['user:456'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -142,7 +142,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['team:def/member'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -152,7 +152,7 @@ class RealtimeGuestTest extends TestCase
$event['permissions'] = ['*'];
$event['data']['channels'] = ['documents.123'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -161,7 +161,7 @@ class RealtimeGuestTest extends TestCase
$event['data']['channels'] = ['documents.789'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -171,19 +171,19 @@ class RealtimeGuestTest extends TestCase
$event['project'] = '2';
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
$this->assertEmpty($receivers);
Realtime::unsubscribe(2, $this->subscriptions, $this->connections);
Realtime\Parser::unsubscribe(2, $this->subscriptions, $this->connections);
$this->assertCount(1, $this->connections);
$this->assertCount(1, $this->subscriptions['1']);
Realtime::unsubscribe(1, $this->subscriptions, $this->connections);
Realtime\Parser::unsubscribe(1, $this->subscriptions, $this->connections);
$this->assertEmpty($this->connections);
$this->assertEmpty($this->subscriptions);

View file

@ -3,7 +3,7 @@
namespace Appwrite\Tests;
use Appwrite\Database\Document;
use Appwrite\Realtime\Realtime;
use Appwrite\Realtime;
use PHPUnit\Framework\TestCase;
class RealtimeTest extends TestCase
@ -21,7 +21,7 @@ class RealtimeTest extends TestCase
public function testUser()
{
Realtime::setUser(new Document([
Realtime\Parser::setUser(new Document([
'$id' => '123',
'memberships' => [
[
@ -40,7 +40,7 @@ class RealtimeTest extends TestCase
]
]));
$roles = Realtime::getRoles();
$roles = Realtime\Parser::getRoles();
$this->assertCount(7, $roles);
$this->assertContains('user:123', $roles);
@ -59,7 +59,7 @@ class RealtimeTest extends TestCase
4 => 'account.456'
];
$channels = Realtime::parseChannels($channels);
$channels = Realtime\Parser::parseChannels($channels);
$this->assertCount(4, $channels);
$this->assertArrayHasKey('files', $channels);
@ -69,7 +69,7 @@ class RealtimeTest extends TestCase
$this->assertArrayNotHasKey('account', $channels);
$this->assertArrayNotHasKey('account.456', $channels);
Realtime::subscribe('1', 1, $roles, $this->subscriptions, $this->connections, $channels);
Realtime\Parser::subscribe('1', 1, $roles, $this->subscriptions, $this->connections, $channels);
$event = [
'project' => '1',
@ -81,7 +81,7 @@ class RealtimeTest extends TestCase
]
];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -91,7 +91,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['role:member'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -101,7 +101,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['user:123'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -111,7 +111,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['team:abc'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -121,7 +121,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['team:abc/administrator'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -131,7 +131,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['team:abc/god'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -141,7 +141,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['team:def'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -151,7 +151,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['team:def/guest'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -161,7 +161,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['user:456'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -170,7 +170,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['team:def/member'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -180,7 +180,7 @@ class RealtimeTest extends TestCase
$event['permissions'] = ['*'];
$event['data']['channels'] = ['documents.123'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -189,7 +189,7 @@ class RealtimeTest extends TestCase
$event['data']['channels'] = ['documents.789'];
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
@ -199,20 +199,20 @@ class RealtimeTest extends TestCase
$event['project'] = '2';
$receivers = Realtime::identifyReceivers(
$receivers = Realtime\Parser::identifyReceivers(
$event,
$this->subscriptions
);
$this->assertEmpty($receivers);
Realtime::unsubscribe(2, $this->subscriptions, $this->connections);
Realtime\Parser::unsubscribe(2, $this->subscriptions, $this->connections);
$this->assertCount(1, $this->connections);
$this->assertCount(7, $this->subscriptions['1']);
Realtime::unsubscribe(1, $this->subscriptions, $this->connections);
Realtime\Parser::unsubscribe(1, $this->subscriptions, $this->connections);
$this->assertEmpty($this->connections);
$this->assertEmpty($this->subscriptions);