Meteor.methods({
	unblockUser({rid, blocked}) {

		check(rid, String);
		check(blocked, String);

		if (!Meteor.userId()) {
			throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'blockUser' });
		}

		const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId());
		const subscription2 = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, blocked);

		if (!subscription || !subscription2) {
			throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'blockUser' });
		}

		RocketChat.models.Subscriptions.unsetBlockedByRoomId(rid, blocked, Meteor.userId());

		return true;
	}
});


const query = {
_id: agentId
};
const options = {
fields: {
name: 1,
username: 1,

keep keep keep replace keep keep keep keep

<template name="emojiInfo">
	{{#if editingEmoji}}
		{{> emojiEdit (emojiToEdit)}}
	{{else}}
		{{#with emoji}}

				{{> emojiPreview name=name extension=extension}}

{{name}}

{{aliases}}

		{{/with}}

			{{#if hasPermission 'manage-emoji'}}
			<button class='button button-block danger delete'> {{_ "Delete"}}</button>
			<button class='button button-block primary edit-emoji'> {{_ "Edit"}}</button>
			{{/if}}

	{{/if}}
</template>


keep keep keep keep replace keep keep keep

/**
 * Sets an user as (non)operator
 * @param {string} _id - User's _id
 * @param {boolean} operator - Flag to set as operator or not
 */
RocketChat.models.Users.setOperator = function(_id, operator) {
	const update = {
		$set: {
			operator
		}
	};

	return this.update(_id, update);
};

/**
 * Gets all online agents
 * @return
 */
RocketChat.models.Users.findOnlineAgents = function() {
	const query = {
		status: {
			$exists: true,
			$ne: 'offline'
		},
		statusLivechat: 'available',
		roles: 'livechat-agent'
	};

	return this.find(query);
};

/**
 * Gets all agents
 * @return
 */
RocketChat.models.Users.findAgents = function() {
	const query = {
		roles: 'livechat-agent'
	};

	return this.find(query);
};

/**
 * Find online users from a list
 * @param {array} userList - array of usernames
 * @return
 */
RocketChat.models.Users.findOnlineUserFromList = function(userList) {
	const query = {
		status: {
			$exists: true,
			$ne: 'offline'
		},
		statusLivechat: 'available',
		roles: 'livechat-agent',
		username: {
			$in: [].concat(userList)
		}
	};

	return this.find(query);
};

/**
 * Get next user agent in order
 * @return {object} User from db
 */
RocketChat.models.Users.getNextAgent = function() {
	const query = {
		status: {
			$exists: true,
			$ne: 'offline'
		},
		statusLivechat: 'available',
		roles: 'livechat-agent'
	};

	const collectionObj = this.model.rawCollection();
	const findAndModify = Meteor.wrapAsync(collectionObj.findAndModify, collectionObj);

	const sort = {
		livechatCount: 1,
		username: 1
	};

	const update = {
		$inc: {
			livechatCount: 1
		}
	};

	const user = findAndModify(query, sort, update);
	if (user && user.value) {
		return {
			agentId: user.value._id,
			username: user.value.username
		};
	} else {
		return null;
	}
};

/**
 * Gets visitor by token
 * @param {string} token - Visitor token
 */
RocketChat.models.Users.getVisitorByToken = function(token, options) {
	const query = {
		'profile.guest': true,
		'profile.token': token
	};

	return this.findOne(query, options);
};

/**
 * Gets visitor by token
 * @param {string} token - Visitor token
 */
RocketChat.models.Users.findVisitorByToken = function(token) {
	const query = {
		'profile.guest': true,
		'profile.token': token
	};

	return this.find(query);
};

/**
 * Change user's livechat status
 * @param {string} token - Visitor token
 */
RocketChat.models.Users.setLivechatStatus = function(userId, status) {
	const query = {
		'_id': userId
	};

	const update = {
		$set: {
			'statusLivechat': status
		}
	};

	return this.update(query, update);
};

/**
 * change all livechat agents livechat status to "not-available"
 */
RocketChat.models.Users.closeOffice = function() {
	self = this;
	self.findAgents().forEach(function(agent) {
		self.setLivechatStatus(agent._id, 'not-available');
	});
};

/**
 * change all livechat agents livechat status to "available"
 */
RocketChat.models.Users.openOffice = function() {
	self = this;
	self.findAgents().forEach(function(agent) {
		self.setLivechatStatus(agent._id, 'available');
	});
};

RocketChat.models.Users.updateLivechatDataByToken = function(token, key, value, overwrite = true) {
	const query = {
		'profile.token': token
	};

	if (!overwrite) {
		const user = this.findOne(query, { fields: { livechatData: 1 } });
		if (user.livechatData && typeof user.livechatData[key] !== 'undefined') {
			return true;
		}
	}

	const update = {
		$set: {
			[`livechatData.${ key }`]: value
		}
	};

	return this.update(query, update);
};

/**
 * Find a visitor by their phone number
 * @return {object} User from db
 */
RocketChat.models.Users.findOneVisitorByPhone = function(phone) {
	const query = {
		'phone.phoneNumber': phone
	};

	return this.findOne(query);
};

/**
 * Get the next visitor name
 * @return {string} The next visitor name
 */
RocketChat.models.Users.getNextVisitorUsername = function() {
	const settingsRaw = RocketChat.models.Settings.model.rawCollection();
	const findAndModify = Meteor.wrapAsync(settingsRaw.findAndModify, settingsRaw);

	const query = {
		_id: 'Livechat_guest_count'
	};

	const update = {
		$inc: {
			value: 1
		}
	};

	const livechatCount = findAndModify(query, null, update);

	return `guest-${ livechatCount.value.value + 1 }`;
};

RocketChat.models.Users.saveGuestById = function(_id, data) {
	const setData = {};
	const unsetData = {};

	if (data.name) {
		if (!_.isEmpty(s.trim(data.name))) {
			setData.name = s.trim(data.name);
		} else {
			unsetData.name = 1;
		}
	}

	if (data.email) {
		if (!_.isEmpty(s.trim(data.email))) {
			setData.visitorEmails = [
				{ address: s.trim(data.email) }
			];
		} else {
			unsetData.visitorEmails = 1;
		}
	}

	if (data.phone) {
		if (!_.isEmpty(s.trim(data.phone))) {
			setData.phone = [
				{ phoneNumber: s.trim(data.phone) }
			];
		} else {
			unsetData.phone = 1;
		}
	}

	const update = {};

	if (!_.isEmpty(setData)) {
		update.$set = setData;
	}

	if (!_.isEmpty(unsetData)) {
		update.$unset = unsetData;
	}

	if (_.isEmpty(update)) {
		return true;
	}

	return this.update({ _id }, update);
};

RocketChat.models.Users.findOneGuestByEmailAddress = function(emailAddress) {
	const query = {
		'visitorEmails.address': new RegExp(`^${ s.escapeRegExp(emailAddress) }$`, 'i')
	};

	return this.findOne(query);
};

RocketChat.models.Users.getAgentInfo = function(agentId) {
	const query = {
		_id: agentId
	};

	const options = {
		fields: {
			name: 1,
			username: 1,
			emails: 1,
			customFields: 1
		}
	};

	return this.findOne(query, options);
};


/* eslint-env mocha */
/* globals expect */
/* eslint no-unused-vars: 0 */

import {getCredentials, api, login, request, credentials, directMessage, log } from '../../data/api-data.js';
import {adminEmail, password} from '../../data/user.js';
import supertest from 'supertest';

describe('[Direct Messages]', function() {
	this.retries(0);

	before(done => getCredentials(done));

	it('/chat.postMessage', (done) => {
		request.post(api('chat.postMessage'))
			.set(credentials)
			.send({
				channel: 'rocket.cat',
				text: 'This message was sent using the API'
			})
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
				expect(res.body).to.have.deep.property('message.msg', 'This message was sent using the API');
				expect(res.body).to.have.deep.property('message.rid');
				directMessage._id = res.body.message.rid;
			})
			.end(done);
	});

	it('/im.setTopic', (done) => {
		request.post(api('im.setTopic'))
			.set(credentials)
			.send({
				roomId: directMessage._id,
				topic: 'a direct message with rocket.cat'
			})
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
			})
			.end(done);
	});

	it('/im.history', (done) => {
		request.get(api('im.history'))
			.set(credentials)
			.query({
				roomId: directMessage._id,
				userId: 'rocket.cat'
			})
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
				expect(res.body).to.have.property('messages');
			})
			.end(done);
	});

	it('/im.list', (done) => {
		request.get(api('im.list'))
			.set(credentials)
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
				expect(res.body).to.have.property('count');
				expect(res.body).to.have.property('total');
			})
			.end(done);
	});

	it('/im.list.everyone', (done) => {
		request.get(api('im.list.everyone'))
			.set(credentials)
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
				expect(res.body).to.have.property('count');
				expect(res.body).to.have.property('total');
			})
			.end(done);
	});

	it('/im.close', (done) => {
		request.post(api('im.close'))
			.set(credentials)
			.send({
				roomId: directMessage._id,
				userId: 'rocket.cat'
			})
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
			})
			.end(done);
	});

	it('/im.open', (done) => {
		request.post(api('im.open'))
			.set(credentials)
			.send({
				roomId: directMessage._id,
				userId: 'rocket.cat'
			})
			.expect('Content-Type', 'application/json')
			.expect(200)
			.expect((res) => {
				expect(res.body).to.have.property('success', true);
			})
			.end(done);
	});
});


<template name="listPrivateGroupsFlex">

{{_ "Private_Groups"}}

					<form class="search-form" role="form">

							<select class="c-select" id="sort">
								<option value="name" selected="{{sortSelected 'name'}}" class="primary-background-color">{{_ "Name"}}</option>
								<option value="ls" selected="{{sortSelected 'ls'}}" class="primary-background-color">{{_ "Last_seen"}}</option>
							</select>

							<input type="text" id="channel-search" class="search" placeholder="{{_ "Search_Private_Groups"}}" autocomplete="off" />

					</form>

{{_ "Private_Groups_list"}}

				{{#each groups}}

							{{name}}

								{{#if hidden}}

								{{/if}}

				{{/each}}

			{{#if hasMore}}

					{{> loading}}

			{{/if}}

</template>


Package.describe({
	name: 'rocketchat:message-star',
	version: '0.0.1',
	summary: 'Star Messages',
	git: ''
});

Package.onUse(function(api) {
	api.use([
		'mongo',
		'ecmascript',
		'underscore',
		'rocketchat:lib'
	]);

	api.use('templating', 'client');

	api.addFiles([
		'client/lib/StarredMessage.js',
		'client/actionButton.js',
		'client/starMessage.js',
		'client/tabBar.js',
		'client/views/starredMessages.html',
		'client/views/starredMessages.js',
		'client/views/stylesheets/messagestar.css'
	], 'client');

	api.addFiles([
		'server/settings.js',
		'server/starMessage.js',
		'server/publications/starredMessages.js',
		'server/startup/indexes.js'
	], 'server');
});


customFields: 1
}
};
return this.findOne(query, options);
};

Meteor.methods({
	'livechat:getInitialData'(visitorToken) {
		const info = {
			enabled: null,
			title: null,
			color: null,
			registrationForm: null,
			room: null,
			triggers: [],
			departments: [],
			allowSwitchingDepartments: null,
			online: true,
			offlineColor: null,
			offlineMessage: null,
			offlineSuccessMessage: null,
			offlineUnavailableMessage: null,
			displayOfflineForm: null,
			showAgentEmail: null,
			videoCall: null
		};

		const room = RocketChat.models.Rooms.findOpenByVisitorToken(visitorToken, {
			fields: {
				name: 1,
				t: 1,
				cl: 1,
				u: 1,
				usernames: 1,
				v: 1,
				servedBy: 1
			}
		}).fetch();

		if (room && room.length > 0) {
			info.room = room[0];
		}

		const initSettings = RocketChat.Livechat.getInitSettings();

		info.title = initSettings.Livechat_title;
		info.color = initSettings.Livechat_title_color;
		info.enabled = initSettings.Livechat_enabled;
		info.registrationForm = initSettings.Livechat_registration_form;
		info.showAgentEmail = initSettings.Livechat_show_agent_email;
		info.offlineTitle = initSettings.Livechat_offline_title;
		info.offlineColor = initSettings.Livechat_offline_title_color;
		info.offlineMessage = initSettings.Livechat_offline_message;
		info.offlineSuccessMessage = initSettings.Livechat_offline_success_message;
		info.offlineUnavailableMessage = initSettings.Livechat_offline_form_unavailable;
		info.displayOfflineForm = initSettings.Livechat_display_offline_form;
		info.language = initSettings.Language;
		info.videoCall = initSettings.Livechat_videocall_enabled === true && initSettings.Jitsi_Enabled === true;
		info.transcript = initSettings.Livechat_enable_transcript;
		info.transcriptMessage = initSettings.Livechat_transcript_message;

		info.agentData = room && room[0] && room[0].servedBy && RocketChat.models.Users.getAgentInfo(room[0].servedBy._id);

		RocketChat.models.LivechatTrigger.findEnabled().forEach((trigger) => {
			info.triggers.push(_.pick(trigger, '_id', 'actions', 'conditions'));
		});

		RocketChat.models.LivechatDepartment.findEnabledWithAgents().forEach((department) => {
			info.departments.push(department);
		});
		info.allowSwitchingDepartments = initSettings.Livechat_allow_switching_departments;

		info.online = RocketChat.models.Users.findOnlineAgents().count() > 0;

		return info;
	}
});


FlowRouter.goToRoomById = (roomId) => {
	const subscription = ChatSubscription.findOne({rid: roomId});
	if (subscription) {
		RocketChat.roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams);
	}
};


Meteor.startup(function() {
	RocketChat.settings.addGroup('IRC', function() {

		// Is this thing on?
		this.add('IRC_Enabled', false, {
			type: 'boolean',
			i18nLabel: 'Enabled',
			i18nDescription: 'IRC_Enabled',
			alert: 'IRC Support is a work in progress. Use on a production system is not recommended at this time.'
		});

		// The IRC host server to talk to
		this.add('IRC_Host', 'irc.freenode.net', {
			type: 'string',
			i18nLabel: 'Host',
			i18nDescription: 'IRC_Hostname'
		});

		// The port to connect on the remote server
		this.add('IRC_Port', 6667, {
			type: 'int',
			i18nLabel: 'Port',
			i18nDescription: 'IRC_Port'
		});

		// Cache size of the messages we send the host IRC server
		this.add('IRC_Message_Cache_Size', 200, {
			type: 'int',
			i18nLabel: 'Message Cache Size',
			i18nDescription: 'IRC_Message_Cache_Size'
		});

		// Expandable box for modifying regular expressions for IRC interaction
		this.section('Regular_Expressions', function() {
			this.add('IRC_RegEx_successLogin', 'Welcome to the freenode Internet Relay Chat Network', {
				type: 'string',
				i18nLabel: 'Login Successful',
				i18nDescription: 'IRC_Login_Success'
			});
			this.add('IRC_RegEx_failedLogin', 'You have not registered', {
				type: 'string',
				i18nLabel: 'Login Failed',
				i18nDescription: 'IRC_Login_Fail'
			});
			this.add('IRC_RegEx_receiveMessage', '^:(\S+)!~\S+ PRIVMSG (\S+) :(.+)$', {
				type: 'string',
				i18nLabel: 'Private Message',
				i18nDescription: 'IRC_Private_Message'
			});
			this.add('IRC_RegEx_receiveMemberList', '^:\S+ \d+ \S+ = #(\S+) :(.*)$', {
				type: 'string',
				i18nLabel: 'Channel User List Start',
				i18nDescription: 'IRC_Channel_Users'
			});
			this.add('IRC_RegEx_endMemberList', '^.+#(\S+) :End of \/NAMES list.$', {
				type: 'string',
				i18nLabel: 'Channel User List End',
				i18nDescription: 'IRC_Channel_Users_End'
			});
			this.add('IRC_RegEx_addMemberToRoom', '^:(\S+)!~\S+ JOIN #(\S+)$', {
				type: 'string',
				i18nLabel: 'Join Channel',
				i18nDescription: 'IRC_Channel_Join'
			});
			this.add('IRC_RegEx_removeMemberFromRoom', '^:(\S+)!~\S+ PART #(\S+)$', {
				type: 'string',
				i18nLabel: 'Leave Channel',
				i18nDescription: 'IRC_Channel_Leave'
			});
			this.add('IRC_RegEx_quitMember', '^:(\S+)!~\S+ QUIT .*$', {
				type: 'string',
				i18nLabel: 'Quit IRC Session',
				i18nDescription: 'IRC_Quit'
			});
		});

	});
});


/* globals msgStream */
function SlackBridgeImport(command, params, item) {
	if (command !== 'slackbridge-import' || !Match.test(params, String)) {
		return;
	}

	const room = RocketChat.models.Rooms.findOneById(item.rid);
	const channel = room.name;
	const user = Meteor.users.findOne(Meteor.userId());

	msgStream.emit(item.rid, {
		_id: Random.id(),
		rid: item.rid,
		u: { username: 'rocket.cat' },
		ts: new Date(),
		msg: TAPi18n.__('SlackBridge_start', {
			postProcess: 'sprintf',
			sprintf: [user.username, channel]
		}, user.language)
	});

	try {
		RocketChat.SlackBridge.importMessages(item.rid, error => {
			if (error) {
				msgStream.emit(item.rid, {
					_id: Random.id(),
					rid: item.rid,
					u: { username: 'rocket.cat' },
					ts: new Date(),
					msg: TAPi18n.__('SlackBridge_error', {
						postProcess: 'sprintf',
						sprintf: [channel, error.message]
					}, user.language)
				});
			} else {
				msgStream.emit(item.rid, {
					_id: Random.id(),
					rid: item.rid,
					u: { username: 'rocket.cat' },
					ts: new Date(),
					msg: TAPi18n.__('SlackBridge_finish', {
						postProcess: 'sprintf',
						sprintf: [channel]
					}, user.language)
				});
			}
		});
	} catch (error) {
		msgStream.emit(item.rid, {
			_id: Random.id(),
			rid: item.rid,
			u: { username: 'rocket.cat' },
			ts: new Date(),
			msg: TAPi18n.__('SlackBridge_error', {
				postProcess: 'sprintf',
				sprintf: [channel, error.message]
			}, user.language)
		});
		throw error;
	}
	return SlackBridgeImport;
}

RocketChat.slashCommands.add('slackbridge-import', SlackBridgeImport);


foreach ($utopia->getRoutes() as $key => $method) {

foreach ($method as $route) { /** @var \Utopia\Route $route */

keep keep keep replace replace keep keep keep keep

<?php

namespace Appwrite\Utopia;

use Exception;
use Utopia\Swoole\Response as SwooleResponse;
use Swoole\Http\Response as SwooleHTTPResponse;
use Appwrite\Database\Document;
use Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response\Model\None;
use Appwrite\Utopia\Response\Model\Any;
use Appwrite\Utopia\Response\Model\BaseList;
use Appwrite\Utopia\Response\Model\Collection;
use Appwrite\Utopia\Response\Model\Continent;
use Appwrite\Utopia\Response\Model\Country;
use Appwrite\Utopia\Response\Model\Currency;
use Appwrite\Utopia\Response\Model\Domain;
use Appwrite\Utopia\Response\Model\Error;
use Appwrite\Utopia\Response\Model\ErrorDev;
use Appwrite\Utopia\Response\Model\Execution;
use Appwrite\Utopia\Response\Model\File;
use Appwrite\Utopia\Response\Model\Func;
use Appwrite\Utopia\Response\Model\Key;
use Appwrite\Utopia\Response\Model\Language;
use Appwrite\Utopia\Response\Model\User;
use Appwrite\Utopia\Response\Model\Session;
use Appwrite\Utopia\Response\Model\Team;
use Appwrite\Utopia\Response\Model\Locale;
use Appwrite\Utopia\Response\Model\Log;
use Appwrite\Utopia\Response\Model\Membership;
use Appwrite\Utopia\Response\Model\Permissions;
use Appwrite\Utopia\Response\Model\Phone;
use Appwrite\Utopia\Response\Model\Platform;
use Appwrite\Utopia\Response\Model\Project;
use Appwrite\Utopia\Response\Model\Rule;
use Appwrite\Utopia\Response\Model\Tag;
use Appwrite\Utopia\Response\Model\Task;
use Appwrite\Utopia\Response\Model\Webhook;

/**
 * @method public function setStatusCode(int $code = 200): Response
 */
class Response extends SwooleResponse
{
    // General
    const MODEL_NONE = 'none';
    const MODEL_ANY = 'any';
    const MODEL_LOG = 'log';
    const MODEL_LOG_LIST = 'logList';
    const MODEL_ERROR = 'error';
    const MODEL_ERROR_DEV = 'errorDev';
    const MODEL_BASE_LIST = 'baseList';
    const MODEL_PERMISSIONS = 'permissions';

    // Database
    const MODEL_COLLECTION = 'collection';
    const MODEL_COLLECTION_LIST = 'collectionList';
    const MODEL_RULE = 'rule';
    const MODEL_DOCUMENT_LIST = 'documentList';

    // Users
    const MODEL_USER = 'user';
    const MODEL_USER_LIST = 'userList';
    const MODEL_SESSION = 'session';
    const MODEL_SESSION_LIST = 'sessionList';
    const MODEL_TOKEN = 'token'; // - Missing

    // Storage
    const MODEL_FILE = 'file';
    const MODEL_FILE_LIST = 'fileList';
    const MODEL_BUCKET = 'bucket'; // - Missing

    // Locale
    const MODEL_LOCALE = 'locale';
    const MODEL_COUNTRY = 'country';
    const MODEL_COUNTRY_LIST = 'countryList';
    const MODEL_CONTINENT = 'continent';
    const MODEL_CONTINENT_LIST = 'continentList';
    const MODEL_CURRENCY = 'currency';
    const MODEL_CURRENCY_LIST = 'currencyList';
    const MODEL_LANGUAGE = 'langauge';
    const MODEL_LANGUAGE_LIST = 'langaugeList';
    const MODEL_PHONE = 'phone';
    const MODEL_PHONE_LIST = 'phoneList';

    // Teams
    const MODEL_TEAM = 'team';
    const MODEL_TEAM_LIST = 'teamList';
    const MODEL_MEMBERSHIP = 'membership';
    const MODEL_MEMBERSHIP_LIST = 'membershipList';

    // Functions
    const MODEL_FUNCTION = 'function';
    const MODEL_FUNCTION_LIST = 'functionList';
    const MODEL_TAG = 'tag';
    const MODEL_TAG_LIST = 'tagList';
    const MODEL_EXECUTION = 'execution';
    const MODEL_EXECUTION_LIST = 'executionList';

    // Project
    const MODEL_PROJECT = 'project';
    const MODEL_PROJECT_LIST = 'projectsList';
    const MODEL_WEBHOOK = 'webhook';
    const MODEL_WEBHOOK_LIST = 'webhookList';
    const MODEL_KEY = 'key';
    const MODEL_KEY_LIST = 'keyList';
    const MODEL_TASK = 'task';
    const MODEL_TASK_LIST = 'taskList';
    const MODEL_PLATFORM = 'platform';
    const MODEL_PLATFORM_LIST = 'platformList';
    const MODEL_DOMAIN = 'domain';
    const MODEL_DOMAIN_LIST = 'domainList';

    /**
     * @var array
     */
    protected $payload = [];

    /**
     * Response constructor.
     *
     * @param float $time
     */
    public function __construct(SwooleHTTPResponse $response)
    {
        $this
            // General
            ->setModel(new None())
            ->setModel(new Any())
            ->setModel(new Error())
            ->setModel(new ErrorDev())
            // Lists
            ->setModel(new BaseList('Collections List', self::MODEL_COLLECTION_LIST, 'collections', self::MODEL_COLLECTION))
            ->setModel(new BaseList('Documents List', self::MODEL_DOCUMENT_LIST, 'documents', self::MODEL_ANY))
            ->setModel(new BaseList('Users List', self::MODEL_USER_LIST, 'users', self::MODEL_USER))
            ->setModel(new BaseList('Sessions List', self::MODEL_SESSION_LIST, 'sessions', self::MODEL_SESSION))
            ->setModel(new BaseList('Logs List', self::MODEL_LOG_LIST, 'logs', self::MODEL_LOG, false))
            ->setModel(new BaseList('Files List', self::MODEL_FILE_LIST, 'files', self::MODEL_FILE))
            ->setModel(new BaseList('Teams List', self::MODEL_TEAM_LIST, 'teams', self::MODEL_TEAM))
            ->setModel(new BaseList('Memberships List', self::MODEL_MEMBERSHIP_LIST, 'memberships', self::MODEL_MEMBERSHIP))
            ->setModel(new BaseList('Functions List', self::MODEL_FUNCTION_LIST, 'functions', self::MODEL_FUNCTION))
            ->setModel(new BaseList('Tags List', self::MODEL_TAG_LIST, 'tags', self::MODEL_TAG))
            ->setModel(new BaseList('Executions List', self::MODEL_EXECUTION_LIST, 'executions', self::MODEL_EXECUTION))
            ->setModel(new BaseList('Projects List', self::MODEL_PROJECT_LIST, 'projects', self::MODEL_PROJECT))
            ->setModel(new BaseList('Webhooks List', self::MODEL_WEBHOOK_LIST, 'webhooks', self::MODEL_WEBHOOK))
            ->setModel(new BaseList('API Keys List', self::MODEL_KEY_LIST, 'keys', self::MODEL_KEY))
            ->setModel(new BaseList('Tasks List', self::MODEL_TASK_LIST, 'tasks', self::MODEL_TASK))
            ->setModel(new BaseList('Platforms List', self::MODEL_PLATFORM_LIST, 'platforms', self::MODEL_PLATFORM))
            ->setModel(new BaseList('Domains List', self::MODEL_DOMAIN_LIST, 'domains', self::MODEL_DOMAIN))
            ->setModel(new BaseList('Countries List', self::MODEL_COUNTRY_LIST, 'countries', self::MODEL_COUNTRY))
            ->setModel(new BaseList('Continents List', self::MODEL_CONTINENT_LIST, 'continents', self::MODEL_CONTINENT))
            ->setModel(new BaseList('Languages List', self::MODEL_LANGUAGE_LIST, 'languages', self::MODEL_LANGUAGE))
            ->setModel(new BaseList('Currencies List', self::MODEL_CURRENCY_LIST, 'currencies', self::MODEL_CURRENCY))
            ->setModel(new BaseList('Phones List', self::MODEL_PHONE_LIST, 'phones', self::MODEL_PHONE))
            // Entities
            ->setModel(new Permissions())
            ->setModel(new Collection())
            ->setModel(new Rule())
            ->setModel(new Log())
            ->setModel(new User())
            ->setModel(new Session())
            ->setModel(new Locale())
            ->setModel(new File())
            ->setModel(new Team())
            ->setModel(new Membership())
            ->setModel(new Func())
            ->setModel(new Tag())
            ->setModel(new Execution())
            ->setModel(new Project())
            ->setModel(new Webhook())
            ->setModel(new Key())
            ->setModel(new Task())
            ->setModel(new Domain())
            ->setModel(new Platform())
            ->setModel(new Country())
            ->setModel(new Continent())
            ->setModel(new Language())
            ->setModel(new Currency())
            ->setModel(new Phone())
            // Verification
            // Recovery
        ;

        parent::__construct($response);
    }

    /**
     * HTTP content types
     */
    const CONTENT_TYPE_YAML = 'application/x-yaml';

    /**
     * List of defined output objects
     */
    protected $models = [];

    /**
     * Set Model Object
     *
     * @return self
     */
    public function setModel(Model $instance): self
    {
        $this->models[$instance->getType()] = $instance;

        return $this;
    }

    /**
     * Get Model Object
     *
     * @return Model
     */
    public function getModel(string $key): Model
    {
        if (!isset($this->models[$key])) {
            throw new Exception('Undefined model: '.$key);
        }

        return $this->models[$key];
    }

    /**
     * Get Models List
     *
     * @return Model[]
     */
    public function getModels(): array
    {
        return $this->models;
    }

    /**
     * Validate response objects and outputs
     *  the response according to given format type
     *
     * @param Document $document
     * @param string $model
     *
     * return void
     */
    public function dynamic(Document $document, string $model): void
    {
        $this->json($this->output($document, $model));
    }

    /**
     * Generate valid response object from document data
     *
     * @param Document $document
     * @param string $model
     *
     * return array
     */
    public function output(Document $document, string $model): array
    {
        $data       = $document;
        $model      = $this->getModel($model);
        $output     = [];

        if ($model->isAny()) {
            return $document->getArrayCopy();
        }

        foreach ($model->getRules() as $key => $rule) {
            if (!$document->isSet($key)) {
                if (!is_null($rule['default'])) {
                    $document->setAttribute($key, $rule['default']);
                } else {
                    throw new Exception('Model '.$model->getName().' is missing response key: '.$key);
                }
            }

            if ($rule['array']) {
                if (!is_array($data[$key])) {
                    throw new Exception($key.' must be an array of type '.$rule['type']);
                }

                foreach ($data[$key] as &$item) {
                    if ($item instanceof Document) {
                        if (!array_key_exists($rule['type'], $this->models)) {
                            throw new Exception('Missing model for rule: '. $rule['type']);
                        }

                        $item = $this->output($item, $rule['type']);
                    }
                }
            }

            $output[$key] = $data[$key];
        }

        $this->payload = $output;

        return $output;
    }

    /**
     * YAML
     *
     * This helper is for sending YAML HTTP response.
     * It sets relevant content type header ('application/x-yaml') and convert a PHP array ($data) to valid YAML using native yaml_parse
     *
     * @see https://en.wikipedia.org/wiki/YAML
     *
     * @param array $data
     *
     * @return void
     */
    public function yaml(array $data): void
    {
        if (!extension_loaded('yaml')) {
            throw new Exception('Missing yaml extension. Learn more at: https://www.php.net/manual/en/book.yaml.php');
        }

        $this
            ->setContentType(Response::CONTENT_TYPE_YAML)
            ->send(yaml_emit($data, YAML_UTF8_ENCODING))
        ;
    }

    /**
     * @return array
     */
    public function getPayload():array
    {
        return $this->payload;
    }
}


const sdk = require('node-appwrite');

// Init SDK
let client = new sdk.Client();

let teams = new sdk.Teams(client);

client
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
    .setKey('919c2d18fb5d4...a2ae413da83346ad2') // Your secret API key
;

let promise = teams.get('[TEAM_ID]');

promise.then(function (response) {
    console.log(response);
}, function (error) {
    console.log(error);
});


<?php

namespace Appwrite\Database\Exception;

class Structure extends \Exception
{
}


<?php

namespace Tests\E2E\Services\Account;

use Tests\E2E\Scopes\Scope;
use Tests\E2E\Scopes\ProjectConsole;
use Tests\E2E\Scopes\SideClient;

class AccountConsoleClientTest extends Scope
{
    use AccountBase;
    use ProjectConsole;
    use SideClient;
}


$format = new Swagger2($utopia, $routes, $models, $keys[$platform], $security[$platform]);

keep keep keep keep add keep keep keep keep

if($platform !== APP_PLATFORM_CONSOLE && !$value->isPublic()) {

<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;

class BaseList extends Model
{
    /**
     * @var string
     */
    protected $name = '';

    /**
     * @var string
     */
    protected $type = '';

    public function __construct(string $name, string $type, string $key, string $model, bool $paging = true)
    {
        $this->name = $name;
        $this->type = $type;

        if ($paging) {
            $this->addRule('sum', [
                'type' => self::TYPE_INTEGER,
                'description' => 'Total sum of items in the list.',
                'example' => '5',
            ]);
        }
        $this->addRule($key, [
            'type' => $model,
            'description' => 'List of '.$key.'.',
            'example' => [],
            'array' => true,
        ]);
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return $this->name;
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return $this->type;
    }
}


FROM python:3.8-alpine

LABEL maintainer="team@appwrite.io"

RUN apk add tar

RUN mkdir /usr/local/src

WORKDIR /usr/local/src/

ENV PIP_TARGET=/usr/local/src/.appwrite


require 'appwrite'

client = Appwrite::Client.new()

client
    .set_endpoint('https://[HOSTNAME_OR_IP]/v1') # Your API Endpoint
    .set_project('5df5acd0d48c2') # Your project ID
    .set_key('919c2d18fb5d4...a2ae413da83346ad2') # Your secret API key
;

storage = Appwrite::Storage.new(client);

response = storage.get_file_preview(file_id: '[FILE_ID]');

puts response


<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;

class Execution extends Model
{
    public function __construct()
    {
        $this
            ->addRule('$id', [
                'type' => self::TYPE_STRING,
                'description' => 'Execution ID.',
                'example' => '5e5ea5c16897e',
            ])
            ->addRule('functionId', [
                'type' => self::TYPE_STRING,
                'description' => 'Function ID.',
                'example' => '5e5ea6g16897e',
            ])
            ->addRule('dateCreated', [
                'type' => self::TYPE_INTEGER,
                'description' => 'The execution creation date in Unix timestamp.',
                'example' => 1592981250,
            ])
            ->addRule('trigger', [
                'type' => self::TYPE_STRING,
                'description' => 'The trigger that caused the function to execute. Possible values can be: `http`, `schedule`, or `event`.',
                'example' => 'http',
            ])
            ->addRule('status', [
                'type' => self::TYPE_STRING,
                'description' => 'The status of the function execution. Possible values can be: `waiting`, `processing`, `completed`, or `failed`.',
                'example' => 'processing',
            ])
            ->addRule('exitCode', [
                'type' => self::TYPE_INTEGER,
                'description' => 'The script exit code.',
                'example' => 0,
            ])
            ->addRule('stdout', [
                'type' => self::TYPE_STRING,
                'description' => 'The script stdout output string.',
                'example' => '',
            ])
            ->addRule('stderr', [
                'type' => self::TYPE_STRING,
                'description' => 'The script stderr output string.',
                'example' => '',
            ])
            ->addRule('time', [
                'type' => self::TYPE_FLOAT,
                'description' => 'The script execution time in seconds.',
                'example' => 0.400,
            ])
        ;
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return 'Execution';
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return Response::MODEL_EXECUTION;
    }
}


->setModel(new BaseList('Teams List', self::MODEL_TEAM_LIST, 'teams', self::MODEL_TEAM))

->setModel(new BaseList('Memberships List', self::MODEL_MEMBERSHIP_LIST, 'memberships', self::MODEL_MEMBERSHIP))

->setModel(new BaseList('Functions List', self::MODEL_FUNCTION_LIST, 'functions', self::MODEL_FUNCTION))

->setModel(new BaseList('Tags List', self::MODEL_TAG_LIST, 'tags', self::MODEL_TAG))

->setModel(new BaseList('Executions List', self::MODEL_EXECUTION_LIST, 'executions', self::MODEL_EXECUTION))

->setModel(new BaseList('Projects List', self::MODEL_PROJECT_LIST, 'projects', self::MODEL_PROJECT))

->setModel(new BaseList('Webhooks List', self::MODEL_WEBHOOK_LIST, 'webhooks', self::MODEL_WEBHOOK))

->setModel(new BaseList('API Keys List', self::MODEL_KEY_LIST, 'keys', self::MODEL_KEY))

->setModel(new BaseList('Tasks List', self::MODEL_TASK_LIST, 'tasks', self::MODEL_TASK))

->setModel(new BaseList('Platforms List', self::MODEL_PLATFORM_LIST, 'platforms', self::MODEL_PLATFORM))

->setModel(new BaseList('Domains List', self::MODEL_DOMAIN_LIST, 'domains', self::MODEL_DOMAIN))

->setModel(new BaseList('Countries List', self::MODEL_COUNTRY_LIST, 'countries', self::MODEL_COUNTRY))

->setModel(new BaseList('Continents List', self::MODEL_CONTINENT_LIST, 'continents', self::MODEL_CONTINENT))

->setModel(new BaseList('Languages List', self::MODEL_LANGUAGE_LIST, 'languages', self::MODEL_LANGUAGE))

->setModel(new BaseList('Currencies List', self::MODEL_CURRENCY_LIST, 'currencies', self::MODEL_CURRENCY))

keep keep keep keep keep replace replace replace replace replace replace keep keep keep keep

->setModel(new BaseList('Projects List', self::MODEL_PROJECT_LIST, 'projects', self::MODEL_PROJECT, true, false))

->setModel(new BaseList('Webhooks List', self::MODEL_WEBHOOK_LIST, 'webhooks', self::MODEL_WEBHOOK, true, false))

->setModel(new BaseList('API Keys List', self::MODEL_KEY_LIST, 'keys', self::MODEL_KEY, true, false))

->setModel(new BaseList('Tasks List', self::MODEL_TASK_LIST, 'tasks', self::MODEL_TASK, true, false))

->setModel(new BaseList('Platforms List', self::MODEL_PLATFORM_LIST, 'platforms', self::MODEL_PLATFORM, true, false))

->setModel(new BaseList('Domains List', self::MODEL_DOMAIN_LIST, 'domains', self::MODEL_DOMAIN, true, false))

<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;

class Key extends Model
{
    public function __construct()
    {
        $this
            ->addRule('$id', [
                'type' => self::TYPE_STRING,
                'description' => 'Key ID.',
                'example' => '5e5ea5c16897e',
            ])
            ->addRule('name', [
                'type' => self::TYPE_STRING,
                'description' => 'Key name.',
                'example' => 'My API Key',
            ])
            ->addRule('scopes', [
                'type' => self::TYPE_STRING,
                'description' => 'Allowed permission scopes.',
                'default' => [],
                'example' => ['users.read', 'documents.write'],
                'array' => true,
            ])
            ->addRule('secret', [
                'type' => self::TYPE_STRING,
                'description' => 'Secret key.',
                'example' => '919c2d18fb5d4...a2ae413da83346ad2',
            ])
        ;
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return 'Key';
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return Response::MODEL_KEY;
    }
}


<?php
return [
    'AF' => 'Afríku',
    'AN' => 'Suðurskautslandið',
    'AS' => 'Asíu',
    'EU' => 'Evrópa',
    'NA' => 'Norður Ameríka',
    'OC' => 'Eyjaálfu',
    'SA' => 'Suður Ameríka',
];


<?php

namespace Tests\E2E\Services\Teams;

use Tests\E2E\Client;

trait TeamsBaseClient
{
    /**
     * @depends testCreateTeam
     */
    public function testGetTeamMemberships($data):array
    {
        $teamUid = $data['teamUid'] ?? '';

        /**
         * Test for SUCCESS
         */
        $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()));

        $this->assertEquals(200, $response['headers']['status-code']);
        $this->assertIsInt($response['body']['sum']);
        $this->assertNotEmpty($response['body']['memberships'][0]['$id']);
        $this->assertEquals($this->getUser()['name'], $response['body']['memberships'][0]['name']);
        $this->assertEquals($this->getUser()['email'], $response['body']['memberships'][0]['email']);
        $this->assertEquals('owner', $response['body']['memberships'][0]['roles'][0]);

        /**
         * Test for FAILURE
         */

        return $data;
    }

    /**
     * @depends testCreateTeam
     */
    public function testCreateTeamMembership($data):array
    {
        $teamUid = $data['teamUid'] ?? '';
        $teamName = $data['teamName'] ?? '';
        $email = uniqid().'friend@localhost.test';

        /**
         * Test for SUCCESS
         */
        $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()), [
            'email' => $email,
            'name' => 'Friend User',
            'roles' => ['admin', 'editor'],
            'url' => 'http://localhost:5000/join-us#title'
        ]);

        $this->assertEquals(201, $response['headers']['status-code']);
        $this->assertNotEmpty($response['body']['$id']);
        $this->assertNotEmpty($response['body']['userId']);
        $this->assertNotEmpty($response['body']['teamId']);
        $this->assertCount(2, $response['body']['roles']);
        $this->assertIsInt($response['body']['joined']);
        $this->assertEquals(false, $response['body']['confirm']);

        $lastEmail = $this->getLastEmail();

        $this->assertEquals($email, $lastEmail['to'][0]['address']);
        $this->assertEquals('Friend User', $lastEmail['to'][0]['name']);
        $this->assertEquals('Invitation to '.$teamName.' Team at '.$this->getProject()['name'], $lastEmail['subject']);

        $secret = substr($lastEmail['text'], strpos($lastEmail['text'], '&secret=', 0) + 8, 256);
        $inviteUid = substr($lastEmail['text'], strpos($lastEmail['text'], '?inviteId=', 0) + 10, 13);
        $userUid = substr($lastEmail['text'], strpos($lastEmail['text'], '&userId=', 0) + 8, 13);

        /**
         * Test for FAILURE
         */
        $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()), [
            'email' => 'dasdkaskdjaskdjasjkd',
            'name' => 'Friend User',
            'roles' => ['admin', 'editor'],
            'url' => 'http://localhost:5000/join-us#title'
        ]);

        $this->assertEquals(400, $response['headers']['status-code']);

        $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()), [
            'email' => $email,
            'name' => 'Friend User',
            'roles' => 'bad string',
            'url' => 'http://localhost:5000/join-us#title'
        ]);

        $this->assertEquals(400, $response['headers']['status-code']);

        $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()), [
            'email' => $email,
            'name' => 'Friend User',
            'roles' => ['admin', 'editor'],
            'url' => 'http://example.com/join-us#title' // bad url
        ]);

        $this->assertEquals(400, $response['headers']['status-code']);

        return [
            'teamUid' => $teamUid,
            'secret' => $secret,
            'inviteUid' => $inviteUid,
            'userUid' => $userUid,
        ];
    }

    /**
     * @depends testCreateTeamMembership
     */
    public function testUpdateTeamMembership($data):array
    {
        $teamUid = $data['teamUid'] ?? '';
        $secret = $data['secret'] ?? '';
        $inviteUid = $data['inviteUid'] ?? '';
        $userUid = $data['userUid'] ?? '';

        /**
         * Test for SUCCESS
         */
        $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$inviteUid.'/status', array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ]), [
            'secret' => $secret,
            'userId' => $userUid,
        ]);

        $this->assertEquals(200, $response['headers']['status-code']);
        $this->assertNotEmpty($response['body']['$id']);
        $this->assertNotEmpty($response['body']['userId']);
        $this->assertNotEmpty($response['body']['teamId']);
        $this->assertCount(2, $response['body']['roles']);
        $this->assertIsInt($response['body']['joined']);
        $this->assertEquals(true, $response['body']['confirm']);

        /**
         * Test for FAILURE
         */
        $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$inviteUid.'/status', array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ]), [
            'secret' => 'sdasdasd',
            'userId' => $userUid,
        ]);

        $this->assertEquals(401, $response['headers']['status-code']);

        $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$inviteUid.'/status', array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ]), [
            'secret' => '',
            'userId' => $userUid,
        ]);

        $this->assertEquals(400, $response['headers']['status-code']);

        $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$inviteUid.'/status', array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ]), [
            'secret' => $secret,
            'userId' => 'sdasd',
        ]);

        $this->assertEquals(401, $response['headers']['status-code']);

        $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$inviteUid.'/status', array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ]), [
            'secret' => $secret,
            'userId' => '',
        ]);

        $this->assertEquals(400, $response['headers']['status-code']);

        return $data;
    }

    /**
     * @depends testUpdateTeamMembership
     */
    public function testDeleteTeamMembership($data):array
    {
        $teamUid = $data['teamUid'] ?? '';
        $inviteUid = $data['inviteUid'] ?? '';

        /**
         * Test for SUCCESS
         */
        $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid.'/memberships/'.$inviteUid, array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()));

        $this->assertEquals(204, $response['headers']['status-code']);
        $this->assertEmpty($response['body']);

        /**
         * Test for FAILURE
         */
        $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$inviteUid, array_merge([
            'origin' => 'http://localhost',
            'content-type' => 'application/json',
            'x-appwrite-project' => $this->getProject()['$id'],
        ], $this->getHeaders()));

        $this->assertEquals(200, $response['headers']['status-code']);
        $this->assertCount(1, $response['body']['memberships']);

        return [];
    }
}


    Bonjour,

    Ce mail vous a été envoyé car {{owner}} vous invite à devenir membre de l'équipe {{team}} sur le projet {{project}}.

    Cliquez sur le lien suivant pour rejoindre l'équipe {{team}}:

{{cta}}

    Si vous n'êtes pas intéressé, vous pouvez ignorer ce message.

    Merci,

    L'équipe {{project}}


*/
protected $any = false;
/**
* @var array
*/
protected $rules = [];

/**
* @var bool
*/
protected $public = true;


<?php

namespace Appwrite\Tests;

use Appwrite\Docker\Compose;
use Exception;
use PHPUnit\Framework\TestCase;

class ComposeTest extends TestCase
{
    /**
     * @var Compose
     */
    protected $object = null;

    public function setUp(): void
    {
        $data = @file_get_contents(__DIR__.'/../../resources/docker/docker-compose.yml');

        if ($data === false) {
            throw new Exception('Failed to read compose file');
        }

        $this->object = new Compose($data);
    }

    public function tearDown(): void
    {
    }

    public function testVersion()
    {
        $this->assertEquals('3', $this->object->getVersion());
    }

    public function testServices()
    {
        $this->assertCount(17, $this->object->getServices());
        $this->assertEquals('appwrite-telegraf', $this->object->getService('telegraf')->getContainerName());
        $this->assertEquals('appwrite', $this->object->getService('appwrite')->getContainerName());
        $this->assertEquals('', $this->object->getService('appwrite')->getImageVersion());
        $this->assertEquals('2.2', $this->object->getService('traefik')->getImageVersion());
        $this->assertEquals(['2080' => '80', '2443' => '443', '8080' => '8080'], $this->object->getService('traefik')->getPorts());
    }

    public function testNetworks()
    {
        $this->assertCount(2, $this->object->getNetworks());
    }

    public function testVolumes()
    {
        $this->assertCount(9, $this->object->getVolumes());
        $this->assertEquals('appwrite-mariadb', $this->object->getVolumes()[0]);
        $this->assertEquals('appwrite-redis', $this->object->getVolumes()[1]);
        $this->assertEquals('appwrite-cache', $this->object->getVolumes()[2]);
    }
}


<?php

namespace Tests\E2E\Scopes;

trait SideNone
{
    public function getHeaders():array
    {
        return [];
    }
}


/// Swift Appwrite SDK
/// Produced by Appwrite SDK Generator
///

var client: Client = Client()

client
    .setEndpoint(endpoint: "https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
    .setProject(value: "5df5acd0d48c2") // Your project ID

var storage: Storage =  Storage(client: client);

var result = storage.getFileDownload(_fileId: "[FILE_ID]");


public function isAny(): bool
{
return $this->any;
}
}

* Should this model be publicly available in docs and spec files?

<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;

class Domain extends Model
{
    public function __construct()
    {
        $this
            ->addRule('$id', [
                'type' => self::TYPE_STRING,
                'description' => 'Domain ID.',
                'example' => '5e5ea5c16897e',
            ])
            ->addRule('domain', [
                'type' => self::TYPE_STRING,
                'description' => 'Domain name.',
                'example' => 'appwrite.company.com',
            ])
            ->addRule('registerable', [
                'type' => self::TYPE_STRING,
                'description' => 'Registerable domain name.',
                'example' => 'company.com',
            ])
            ->addRule('tld', [
                'type' => self::TYPE_STRING,
                'description' => 'TLD name.',
                'example' => 'com',
            ])
            ->addRule('verification', [
                'type' => self::TYPE_BOOLEAN,
                'description' => 'Verification process status.',
                'example' => true,
            ])
        ;
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return 'Domain';
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return Response::MODEL_DOMAIN;
    }
}


package main

import (
    "fmt"
    "github.com/appwrite/sdk-for-go"
)

func main() {
    var client := appwrite.Client{}

    client.SetProject("5df5acd0d48c2") // Your project ID
    client.SetKey("919c2d18fb5d4...a2ae413da83346ad2") // Your secret API key

    var service := appwrite.Database{
        client: &client
    }

    var response, error := service.ListCollections("[SEARCH]", 0, 0, "ASC")

    if error != nil {
        panic(error)
    }

    fmt.Println(response)
}


package main

import (
    "fmt"
    "github.com/appwrite/sdk-for-go"
)

func main() {
    var client := appwrite.Client{}

    client.SetProject("5df5acd0d48c2") // Your project ID
    client.SetKey("919c2d18fb5d4...a2ae413da83346ad2") // Your secret API key

    var service := appwrite.Functions{
        client: &client
    }

    var response, error := service.DeleteTag("[FUNCTION_ID]", "[TAG_ID]")

    if error != nil {
        panic(error)
    }

    fmt.Println(response)
}


<?php

use Appwrite\Database\Document;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Config\Config;

App::get('/v1/locale')
    ->desc('Get User Locale')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'get')
    ->label('sdk.description', '/docs/references/locale/get-locale.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_LOCALE)
    ->action(function ($request, $response, $locale, $geodb) {
        /** @var Utopia\Swoole\Request $request */
        /** @var Appwrite\Utopia\Response $response */
        /** @var Utopia\Locale\Locale $locale */
        /** @var MaxMind\Db\Reader $geodb */

        $eu = Config::getParam('locale-eu');
        $currencies = Config::getParam('locale-currencies');
        $output = [];
        $ip = $request->getIP();
        $time = (60 * 60 * 24 * 45); // 45 days cache
        $countries = $locale->getText('countries');
        $continents = $locale->getText('continents');

        $output['ip'] = $ip;

        $currency = null;

        $record = $geodb->get($ip);

        if ($record) {
            $output['countryCode'] = $record['country']['iso_code'];
            $output['country'] = (isset($countries[$record['country']['iso_code']])) ? $countries[$record['country']['iso_code']] : $locale->getText('locale.country.unknown');
            $output['continent'] = (isset($continents[$record['continent']['code']])) ? $continents[$record['continent']['code']] : $locale->getText('locale.country.unknown');
            $output['continentCode'] = $record['continent']['code'];
            $output['eu'] = (\in_array($record['country']['iso_code'], $eu)) ? true : false;

            foreach ($currencies as $code => $element) {
                if (isset($element['locations']) && isset($element['code']) && \in_array($record['country']['iso_code'], $element['locations'])) {
                    $currency = $element['code'];
                }
            }

            $output['currency'] = $currency;
        } else {
            $output['countryCode'] = '--';
            $output['country'] = $locale->getText('locale.country.unknown');
            $output['continent'] = $locale->getText('locale.country.unknown');
            $output['continentCode'] = '--';
            $output['eu'] = false;
            $output['currency'] = $currency;
        }

        $response
            ->addHeader('Cache-Control', 'public, max-age='.$time)
            ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time).' GMT') // 45 days cache
        ;
        $response->dynamic(new Document($output), Response::MODEL_LOCALE);
    }, ['request', 'response', 'locale', 'geodb']);

App::get('/v1/locale/countries')
    ->desc('List Countries')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'getCountries')
    ->label('sdk.description', '/docs/references/locale/get-countries.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_COUNTRY_LIST)
    ->action(function ($response, $locale) {
        /** @var Appwrite\Utopia\Response $response */
        /** @var Utopia\Locale\Locale $locale */

        $list = $locale->getText('countries'); /* @var $list array */
        $output = [];

        \asort($list); // sort by abc per locale

        foreach ($list as $key => $value) {
            $output[] = new Document([
                'name' => $value,
                'code' => $key,
            ]);
        }

        $response->dynamic(new Document(['countries' => $output, 'sum' => \count($output)]), Response::MODEL_COUNTRY_LIST);
    }, ['response', 'locale']);

App::get('/v1/locale/countries/eu')
    ->desc('List EU Countries')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'getCountriesEU')
    ->label('sdk.description', '/docs/references/locale/get-countries-eu.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_COUNTRY_LIST)
    ->action(function ($response, $locale) {
        /** @var Appwrite\Utopia\Response $response */
        /** @var Utopia\Locale\Locale $locale */

        $list = $locale->getText('countries'); /* @var $countries array */
        $eu = Config::getParam('locale-eu');
        $output = [];

        \asort($list);

        foreach ($eu as $code) {
            if (\array_key_exists($code, $list)) {
                $output[] = new Document([
                    'name' => $list[$code],
                    'code' => $code,
                ]);
            }
        }

        $response->dynamic(new Document(['countries' => $output, 'sum' => \count($output)]), Response::MODEL_COUNTRY_LIST);
    }, ['response', 'locale']);

App::get('/v1/locale/countries/phones')
    ->desc('List Countries Phone Codes')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'getCountriesPhones')
    ->label('sdk.description', '/docs/references/locale/get-countries-phones.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_PHONE_LIST)
    ->action(function ($response, $locale) {
        /** @var Appwrite\Utopia\Response $response */
        /** @var Utopia\Locale\Locale $locale */

        $list = Config::getParam('locale-phones'); /* @var $list array */
        $countries = $locale->getText('countries'); /* @var $countries array */
        $output = [];

        \asort($list);

        foreach ($list as $code => $name) {
            if (\array_key_exists($code, $countries)) {
                $output[] = new Document([
                    'code' => '+'.$list[$code],
                    'countryCode' => $code,
                    'countryName' => $countries[$code],
                ]);
            }
        }

        $response->dynamic(new Document(['phones' => $output, 'sum' => \count($output)]), Response::MODEL_PHONE_LIST);
    }, ['response', 'locale']);

App::get('/v1/locale/continents')
    ->desc('List Continents')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'getContinents')
    ->label('sdk.description', '/docs/references/locale/get-continents.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_CONTINENT_LIST)
    ->action(function ($response, $locale) {
        /** @var Appwrite\Utopia\Response $response */
        /** @var Utopia\Locale\Locale $locale */

        $list = $locale->getText('continents'); /* @var $list array */

        \asort($list);

        foreach ($list as $key => $value) {
            $output[] = new Document([
                'name' => $value,
                'code' => $key,
            ]);
        }

        $response->dynamic(new Document(['continents' => $output, 'sum' => \count($output)]), Response::MODEL_CONTINENT_LIST);
    }, ['response', 'locale']);

App::get('/v1/locale/currencies')
    ->desc('List Currencies')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'getCurrencies')
    ->label('sdk.description', '/docs/references/locale/get-currencies.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_CURRENCY_LIST)
    ->action(function ($response) {
        /** @var Appwrite\Utopia\Response $response */

        $list = Config::getParam('locale-currencies');

        $list = array_map(function($node) {
            return new Document($node);
        }, $list);

        $response->dynamic(new Document(['currencies' => $list, 'sum' => \count($list)]), Response::MODEL_CURRENCY_LIST);
    }, ['response']);

App::get('/v1/locale/languages')
    ->desc('List Languages')
    ->groups(['api', 'locale'])
    ->label('scope', 'locale.read')
    ->label('sdk.platform', [APP_PLATFORM_CLIENT, APP_PLATFORM_SERVER])
    ->label('sdk.namespace', 'locale')
    ->label('sdk.method', 'getLanguages')
    ->label('sdk.description', '/docs/references/locale/get-languages.md')
    ->label('sdk.response.code', Response::STATUS_CODE_OK)
    ->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
    ->label('sdk.response.model', Response::MODEL_LANGUAGE_LIST)
    ->action(function ($response) {
        /** @var Appwrite\Utopia\Response $response */

        $list = Config::getParam('locale-languages');

        $list = array_map(function($node) {
            return new Document($node);
        }, $list);

        $response->dynamic(new Document(['languages' => $list, 'sum' => \count($list)]), Response::MODEL_LANGUAGE_LIST);
    }, ['response']);


public function __construct(string $name, string $type, string $key, string $model, bool $paging = true)

public function __construct(string $name, string $type, string $key, string $model, bool $paging = true, bool $public = true)

<?php

namespace Appwrite\Utopia\Response;

abstract class Model
{
    const TYPE_STRING = 'string';
    const TYPE_INTEGER = 'integer';
    const TYPE_FLOAT = 'float';
    const TYPE_BOOLEAN = 'boolean';
    const TYPE_JSON = 'json';

    /**
     * @var bool
     */
    protected $none = false;

    /**
     * @var bool
     */
    protected $any = false;

    /**
     * @var array
     */
    protected $rules = [];

    /**
     * Get Name
     *
     * @return string
     */
    abstract public function getName():string;

    /**
     * Get Collection
     *
     * @return string
     */
    abstract public function getType():string;

    /**
     * Get Rules
     *
     * @return array
     */
    public function getRules(): array
    {
        return $this->rules;
    }

    /**
     * Add a New Rule
     */
    protected function addRule(string $key, array $options): self
    {
        $this->rules[$key] = array_merge([
            'require' => true,
            'type' => '',
            'description' => '',
            'default' => null,
            'example' => '',
            'array' => false,
        ], $options);

        return $this;
    }

    public function getRequired()
    {
        $list = [];

        foreach($this->rules as $key => $rule) {
            if(isset($rule['require']) || $rule['require']) {
                $list[] = $key;
            }
        }

        return $list;
    }

    /**
     * Is None
     *
     * Use to check if response is empty
     *
     * @return bool
     */
    public function isNone(): bool
    {
        return $this->none;
    }

    /**
     * Is Any
     *
     * Use to check if response is a wildcard
     *
     * @return bool
     */
    public function isAny(): bool
    {
        return $this->any;
    }
}


    こんにちは。

    {{owner}} さんから {{project}} プロジェクトの {{team}} チームへの参加招待が届きました。

    下記のリンクから {{team}} へ参加してください。

{{cta}}

    お手数ですが、心当たりがない場合このメールを破棄してください。

    ありがとうございます。

    {{project}} チーム


<?php

return [
    'AF' => 'Africa',
    'AN' => 'Antartide',
    'AS' => 'Asia',
    'EU' => 'Europa',
    'NA' => 'Nord America',
    'OC' => 'Oceania',
    'SA' => 'Sud America',
];


<?php

use Appwrite\Client;
use Appwrite\Services\Functions;

$client = new Client();

$client
    ->setProject('5df5acd0d48c2') // Your project ID
    ->setKey('919c2d18fb5d4...a2ae413da83346ad2') // Your secret API key
;

$functions = new Functions($client);

$result = $functions->listExecutions('[FUNCTION_ID]');


{
$this->name = $name;
$this->type = $type;
if ($paging) {
$this->addRule('sum', [


package .services;

import okhttp3.Call;
import .Client;
import .enums.OrderType;

import java.io.File;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import static java.util.Map.entry;

public class Avatars extends Service {
    public Avatars(Client client){
        super(client);
    }

     /// Get Browser Icon
     /*
     * You can use this endpoint to show different browser icons to your users.
     * The code argument receives the browser code as it appears in your user
     * /account/sessions endpoint. Use width, height and quality arguments to
     * change the output settings.
     */
    public Call getBrowser(String code, int width, int height, int quality) {
        final String path = "/avatars/browsers/{code}".replace("{code}", code);

        final Map<String, Object> params = Map.ofEntries(
            entry("width", width),
            entry("height", height),
            entry("quality", quality)
        );

        final Map<String, String> headers = Map.ofEntries(
            entry("content-type", "application/json")
        );

        return client.call("GET", path, headers, params);
    }

     /// Get Credit Card Icon
     /*
     * Need to display your users with your billing method or their payment
     * methods? The credit card endpoint will return you the icon of the credit
     * card provider you need. Use width, height and quality arguments to change
     * the output settings.
     */
    public Call getCreditCard(String code, int width, int height, int quality) {
        final String path = "/avatars/credit-cards/{code}".replace("{code}", code);

        final Map<String, Object> params = Map.ofEntries(
            entry("width", width),
            entry("height", height),
            entry("quality", quality)
        );

        final Map<String, String> headers = Map.ofEntries(
            entry("content-type", "application/json")
        );

        return client.call("GET", path, headers, params);
    }

     /// Get Favicon
     /*
     * Use this endpoint to fetch the favorite icon (AKA favicon) of a  any remote
     * website URL.
     */
    public Call getFavicon(String url) {
        final String path = "/avatars/favicon";

        final Map<String, Object> params = Map.ofEntries(
            entry("url", url)
        );

        final Map<String, String> headers = Map.ofEntries(
            entry("content-type", "application/json")
        );

        return client.call("GET", path, headers, params);
    }

     /// Get Country Flag
     /*
     * You can use this endpoint to show different country flags icons to your
     * users. The code argument receives the 2 letter country code. Use width,
     * height and quality arguments to change the output settings.
     */
    public Call getFlag(String code, int width, int height, int quality) {
        final String path = "/avatars/flags/{code}".replace("{code}", code);

        final Map<String, Object> params = Map.ofEntries(
            entry("width", width),
            entry("height", height),
            entry("quality", quality)
        );

        final Map<String, String> headers = Map.ofEntries(
            entry("content-type", "application/json")
        );

        return client.call("GET", path, headers, params);
    }

     /// Get Image from URL
     /*
     * Use this endpoint to fetch a remote image URL and crop it to any image size
     * you want. This endpoint is very useful if you need to crop and display
     * remote images in your app or in case you want to make sure a 3rd party
     * image is properly served using a TLS protocol.
     */
    public Call getImage(String url, int width, int height) {
        final String path = "/avatars/image";

        final Map<String, Object> params = Map.ofEntries(
            entry("url", url),
            entry("width", width),
            entry("height", height)
        );

        final Map<String, String> headers = Map.ofEntries(
            entry("content-type", "application/json")
        );

        return client.call("GET", path, headers, params);
    }

     /// Get QR Code
     /*
     * Converts a given plain text to a QR code image. You can use the query
     * parameters to change the size and style of the resulting image.
     */
    public Call getQR(String text, int size, int margin, int download) {
        final String path = "/avatars/qr";

        final Map<String, Object> params = Map.ofEntries(
            entry("text", text),
            entry("size", size),
            entry("margin", margin),
            entry("download", download)
        );

        final Map<String, String> headers = Map.ofEntries(
            entry("content-type", "application/json")
        );

        return client.call("GET", path, headers, params);
    }
}


<?php
// When there are multiple alternative correct country names please follow https://sv.wikipedia.org/wiki/ISO_3166
return [
    'AF' => 'Afghanistan',
    'AO' => 'Angola',
    'AL' => 'Albanien',
    'AD' => 'Andorra',
    'AE' => 'Förenade Arabemiraten',
    'AR' => 'Argentina',
    'AM' => 'Armenien',
    'AG' => 'Antigua och Barbuda',
    'AU' => 'Australien',
    'AT' => 'Österrike',
    'AZ' => 'Azerbajdzjan',
    'BI' => 'Burundi',
    'BE' => 'Belgien',
    'BJ' => 'Benin',
    'BF' => 'Burkina Faso',
    'BD' => 'Bangladesh',
    'BG' => 'Bulgarien',
    'BH' => 'Bahrain',
    'BS' => 'Bahamas',
    'BA' => 'Bosnien och Hercegovina',
    'BY' => 'Vitryssland',
    'BZ' => 'Belize',
    'BO' => 'Bolivia',
    'BR' => 'Brasilien',
    'BB' => 'Barbados',
    'BN' => 'Brunei',
    'BT' => 'Bhutan',
    'BW' => 'Botswana',
    'CF' => 'Centralafrikanska republiken',
    'CA' => 'Kanada',
    'CH' => 'Schweiz',
    'CL' => 'Chile',
    'CN' => 'Kina',
    'CI' => 'Elfenbenskusten',
    'CM' => 'Kamerun',
    'CD' => 'Kongo-Kinshasa',
    'CG' => 'Kongo-Brazzaville',
    'CO' => 'Colombia',
    'KM' => 'Komorerna',
    'CV' => 'Kap Verde',
    'CR' => 'Costa Rica',
    'CU' => 'Kuba',
    'CY' => 'Cypern',
    'CZ' => 'Tjeckien',
    'DE' => 'Tyskland',
    'DJ' => 'Djibouti',
    'DM' => 'Dominica',
    'DK' => 'Danmark',
    'DO' => 'Dominikanska republiken',
    'DZ' => 'Algeriet',
    'EC' => 'Ecuador',
    'EG' => 'Egypten',
    'ER' => 'Eritrea',
    'ES' => 'Spanien',
    'EE' => 'Estland',
    'ET' => 'Etiopien',
    'FI' => 'Finland',
    'FJ' => 'Fiji',
    'FR' => 'Frankrike',
    'FM' => 'Mikronesien',
    'GA' => 'Gabon',
    'GB' => 'Storbritannien',
    'GE' => 'Georgien',
    'GH' => 'Ghana',
    'GN' => 'Guinea',
    'GM' => 'Gambia',
    'GW' => 'Guinea-Bissau',
    'GQ' => 'Ekvatorialguinea',
    'GR' => 'Grekland',
    'GD' => 'Grenada',
    'GT' => 'Guatemala',
    'GY' => 'Guyana',
    'HN' => 'Honduras',
    'HR' => 'Kroatien',
    'HT' => 'Haiti',
    'HU' => 'Ungern',
    'ID' => 'Indonesien',
    'IN' => 'Indien',
    'IE' => 'Irland',
    'IR' => 'Iran',
    'IQ' => 'Irak',
    'IS' => 'Island',
    'IL' => 'Israel',
    'IT' => 'Italien',
    'JM' => 'Jamaika',
    'JO' => 'Jordanien',
    'JP' => 'Japan',
    'KZ' => 'Kazakstan',
    'KE' => 'Kenya',
    'KG' => 'Kirgizistan',
    'KH' => 'Kambodja',
    'KI' => 'Kiribati',
    'KN' => 'Saint Kitts och Nevis',
    'KR' => 'Sydkorea',
    'KW' => 'Kuwait',
    'LA' => 'Laos',
    'LB' => 'Libanon',
    'LR' => 'Liberia',
    'LY' => 'Libyen',
    'LC' => 'Saint Lucia',
    'LI' => 'Liechtenstein',
    'LK' => 'Sri Lanka',
    'LS' => 'Lesotho',
    'LT' => 'Litauen',
    'LU' => 'Luxemburg',
    'LV' => 'Lettland',
    'MA' => 'Marocko',
    'MC' => 'Monaco',
    'MD' => 'Moldavien',
    'MG' => 'Madagaskar',
    'MV' => 'Maldiverna',
    'MX' => 'Mexiko',
    'MH' => 'Marshallöarna',
    'MK' => 'Nordmakedonien',
    'ML' => 'Mali',
    'MT' => 'Malta',
    'MM' => 'Myanmar',
    'ME' => 'Montenegro',
    'MN' => 'Mongoliet',
    'MZ' => 'Moçambique',
    'MR' => 'Mauretanien',
    'MU' => 'Mauritius',
    'MW' => 'Malawi',
    'MY' => 'Malaysia',
    'NA' => 'Namibia',
    'NE' => 'Niger',
    'NG' => 'Nigeria',
    'NI' => 'Nicaragua',
    'NL' => 'Nederländerna',
    'NO' => 'Norge',
    'NP' => 'Nepal',
    'NR' => 'Nauru',
    'NZ' => 'Nya Zeeland',
    'OM' => 'Oman',
    'PK' => 'Pakistan',
    'PA' => 'Panama',
    'PE' => 'Peru',
    'PH' => 'Filippinerna',
    'PW' => 'Palau',
    'PG' => 'Papua Nya Guinea',
    'PL' => 'Polen',
    'KP' => 'Nordkorea',
    'PT' => 'Portugal',
    'PY' => 'Paraguay',
    'QA' => 'Qatar',
    'RO' => 'Rumänien',
    'RU' => 'Ryssland',
    'RW' => 'Rwanda',
    'SA' => 'Saudiarabien',
    'SD' => 'Sudan',
    'SN' => 'Senegal',
    'SG' => 'Singapore',
    'SB' => 'Salomonöarna',
    'SL' => 'Sierra Leone',
    'SV' => 'El Salvador',
    'SM' => 'San Marino',
    'SO' => 'Somalia',
    'RS' => 'Serbien',
    'SS' => 'Sydsudan',
    'ST' => 'São Tomé och Príncipe',
    'SR' => 'Surinam',
    'SK' => 'Slovakien',
    'SI' => 'Slovenien',
    'SE' => 'Sverige',
    'SZ' => 'Swaziland',
    'SC' => 'Seychellerna',
    'SY' => 'Syrien',
    'TD' => 'Tchad',
    'TG' => 'Togo',
    'TH' => 'Thailand',
    'TJ' => 'Tadzjikistan',
    'TM' => 'Turkmenistan',
    'TL' => 'Timor-Leste',
    'TO' => 'Tonga',
    'TT' => 'Trinidad och Tobago',
    'TN' => 'Tunisien',
    'TR' => 'Turkiet',
    'TV' => 'Tuvalu',
    'TZ' => 'Tanzania',
    'UG' => 'Uganda',
    'UA' => 'Ukraina',
    'UY' => 'Uruguay',
    'US' => 'Amerikas Förenta Stater',
    'UZ' => 'Uzbekistan',
    'VA' => 'Vatikanstaten',
    'VC' => 'Sankt Vincent och Grenadinerna',
    'VE' => 'Venezuela',
    'VN' => 'Vietnam',
    'VU' => 'Vanuatu',
    'WS' => 'Samoa',
    'YE' => 'Jemen',
    'ZA' => 'Sydafrika',
    'ZM' => 'Zambia',
    'ZW' => 'Zimbabwe',
];


use Appwrite\Utopia\Response\Model;
class Domain extends Model
{
public function __construct()
{
$this
->addRule('$id', [

/**
* @var bool
*/
protected $public = false;

<?php

use Appwrite\Spec\Spec;
use Appwrite\Specification\Format\OpenAPI3;
use Appwrite\Specification\Format\Swagger2;
use Appwrite\Specification\Specification;
use Appwrite\Template\Template;
use Utopia\App;
use Utopia\View;
use Utopia\Config\Config;
use Utopia\Exception;
use Utopia\Validator\WhiteList;
use Utopia\Validator\Range;

App::init(function ($layout) {
    /** @var Utopia\View $layout */

    $header = new View(__DIR__.'/../../views/home/comps/header.phtml');
    $footer = new View(__DIR__.'/../../views/home/comps/footer.phtml');

    $footer
        ->setParam('version', App::getEnv('_APP_VERSION', 'UNKNOWN'))
    ;

    $layout
        ->setParam('title', APP_NAME)
        ->setParam('description', '')
        ->setParam('class', 'home')
        ->setParam('platforms', Config::getParam('platforms'))
        ->setParam('header', [$header])
        ->setParam('footer', [$footer])
    ;
}, ['layout'], 'home');

App::shutdown(function ($response, $layout) {
    /** @var Appwrite\Utopia\Response $response */
    /** @var Utopia\View $layout */

    $response->html($layout->render());
}, ['response', 'layout'], 'home');

App::get('/')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($response) {
        /** @var Appwrite\Utopia\Response $response */

        $response->redirect('/auth/signin');
    }, ['response']);

App::get('/auth/signin')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/signin.phtml');

        $layout
            ->setParam('title', 'Sign In - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/auth/signup')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */
        $page = new View(__DIR__.'/../../views/home/auth/signup.phtml');

        $layout
            ->setParam('title', 'Sign Up - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/auth/recovery')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/recovery.phtml');

        $layout
            ->setParam('title', 'Password Recovery - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/auth/confirm')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/confirm.phtml');

        $layout
            ->setParam('title', 'Account Confirmation - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/auth/join')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/join.phtml');

        $layout
            ->setParam('title', 'Invitation - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/auth/recovery/reset')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/recovery/reset.phtml');

        $layout
            ->setParam('title', 'Password Reset - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/auth/oauth2/success')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/oauth2.phtml');

        $layout
            ->setParam('title', APP_NAME)
            ->setParam('body', $page)
            ->setParam('header', [])
            ->setParam('footer', [])
        ;
    }, ['layout']);

App::get('/auth/oauth2/failure')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->action(function ($layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/home/auth/oauth2.phtml');

        $layout
            ->setParam('title', APP_NAME)
            ->setParam('body', $page)
            ->setParam('header', [])
            ->setParam('footer', [])
        ;
    }, ['layout']);

App::get('/error/:code')
    ->groups(['web', 'home'])
    ->label('permission', 'public')
    ->label('scope', 'home')
    ->param('code', null, new \Utopia\Validator\Numeric(), 'Valid status code number', false)
    ->action(function ($code, $layout) {
        /** @var Utopia\View $layout */

        $page = new View(__DIR__.'/../../views/error.phtml');

        $page
            ->setParam('code', $code)
        ;

        $layout
            ->setParam('title', 'Error'.' - '.APP_NAME)
            ->setParam('body', $page);
    }, ['layout']);

App::get('/specs/:format')
    ->groups(['web', 'home'])
    ->label('scope', 'public')
    ->label('docs', false)
    ->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)
    ->action(function ($format, $platform, $utopia, $request, $response) {
        /** @var Utopia\App $utopia */
        /** @var Utopia\Swoole\Request $request */
        /** @var Appwrite\Utopia\Response $response */

        $platforms = [
            'client' => APP_PLATFORM_CLIENT,
            'server' => APP_PLATFORM_SERVER,
            'console' => APP_PLATFORM_CONSOLE,
        ];

        $routes = [];
        $models = [];

        $keys = [
            APP_PLATFORM_CLIENT => [
                'Project' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Project',
                    'description' => 'Your project ID',
                    'in' => 'header',
                ],
                'Locale' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Locale',
                    'description' => '',
                    'in' => 'header',
                ],
            ],
            APP_PLATFORM_SERVER => [
                'Project' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Project',
                    'description' => 'Your project ID',
                    'in' => 'header',
                ],
                'Key' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Key',
                    'description' => 'Your secret API key',
                    'in' => 'header',
                ],
                'Locale' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Locale',
                    'description' => '',
                    'in' => 'header',
                ],
            ],
            APP_PLATFORM_CONSOLE => [
                'Project' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Project',
                    'description' => 'Your project ID',
                    'in' => 'header',
                ],
                'Key' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Key',
                    'description' => 'Your secret API key',
                    'in' => 'header',
                ],
                'Locale' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Locale',
                    'description' => '',
                    'in' => 'header',
                ],
                'Mode' => [
                    'type' => 'apiKey',
                    'name' => 'X-Appwrite-Mode',
                    'description' => '',
                    'in' => 'header',
                ],
            ],
        ];

        $security = [
            APP_PLATFORM_CLIENT => ['Project' => []],
            APP_PLATFORM_SERVER => ['Project' => [], 'Key' => []],
            APP_PLATFORM_CONSOLE => ['Project' => [], 'Key' => []],
        ];

        foreach ($utopia->getRoutes() as $key => $method) {
            foreach ($method as $route) { /** @var \Utopia\Route $route */
                var_dump($route->getURL());

                if (!$route->getLabel('docs', true)) {
                    continue;
                }

                if ($route->getLabel('sdk.mock', false)) {
                    continue;
                }

                if (empty($route->getLabel('sdk.namespace', null))) {
                    continue;
                }

                if ($platform !== APP_PLATFORM_CONSOLE && !\in_array($platforms[$platform], $route->getLabel('sdk.platform', []))) {
                    continue;
                }

                $routes[] = $route;
                $model = $response->getModel($route->getLabel('sdk.response.model', 'none'));

                if($model) {
                    $models[$model->getType()] = $model;
                }
            }
        }

        $models = $response->getModels();

        switch ($format) {
            case 'swagger2':
                $format = new Swagger2($utopia, $routes, $models, $keys[$platform], $security[$platform]);
                break;

            case 'open-api3':
                $format = new OpenAPI3($utopia, $routes, $models, $keys[$platform], $security[$platform]);
                break;

            default:
                throw new Exception('Format not found', 404);
                break;
        }

        $specs = new Specification($format);

        $format
            ->setParam('name', APP_NAME)
            ->setParam('description', 'Appwrite backend as a service cuts up to 70% of the time and costs required for building a modern application. We abstract and simplify common development tasks behind a REST APIs, to help you develop your app in a fast and secure way. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs)')
            ->setParam('endpoint', App::getEnv('_APP_HOME', $request->getProtocol().'://'.$request->getHostname()).'/v1')
            ->setParam('version', APP_VERSION_STABLE)
            ->setParam('terms', App::getEnv('_APP_HOME', $request->getProtocol().'://'.$request->getHostname()).'/policy/terms')
            ->setParam('support.email', App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM))
            ->setParam('support.url', App::getEnv('_APP_HOME', $request->getProtocol().'://'.$request->getHostname()).'/support')
            ->setParam('contact.name', APP_NAME.' Team')
            ->setParam('contact.email', App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM))
            ->setParam('contact.url', App::getEnv('_APP_HOME', $request->getProtocol().'://'.$request->getHostname()).'/support')
            ->setParam('license.name', 'BSD-3-Clause')
            ->setParam('license.url', 'https://raw.githubusercontent.com/appwrite/appwrite/master/LICENSE')
            ->setParam('docs.description', 'Full API docs, specs and tutorials')
            ->setParam('docs.url', App::getEnv('_APP_HOME', $request->getProtocol().'://'.$request->getHostname()).'/docs')
        ;

        $response
            ->json($specs->parse());
    }, ['utopia', 'request', 'response']);


<?php

use Appwrite\Client;
use Appwrite\Services\Health;

$client = new Client();

$client
    ->setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    ->setProject('5df5acd0d48c2') // Your project ID
    ->setKey('919c2d18fb5d4...a2ae413da83346ad2') // Your secret API key
;

$health = new Health($client);

$result = $health->getCache();


    Здравствуйте, {{name}},

    Перейдите по ссылке, чтобы подтвердить свой адрес электронной почты.

{{cta}}

    Если вы не запрашивали подтверждение этого адреса, проигнорируйте это сообщение.

    Спасибо,

    команда {{project}}


import 'package:appwrite/appwrite.dart';

void main() { // Init SDK
  Client client = Client();
  Account account = Account(client);

  client
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
  ;

  Future result = account.updatePrefs(
    prefs: {},
  );

  result
    .then((response) {
      print(response);
    }).catchError((error) {
      print(error.response);
  });
}


<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;

class Key extends Model
{
    public function __construct()
    {
        $this
            ->addRule('$id', [
                'type' => self::TYPE_STRING,
                'description' => 'Key ID.',
                'example' => '5e5ea5c16897e',
            ])
            ->addRule('name', [
                'type' => self::TYPE_STRING,
                'description' => 'Key name.',
                'example' => 'My API Key',
            ])
            ->addRule('scopes', [
                'type' => self::TYPE_STRING,
                'description' => 'Allowed permission scopes.',
                'default' => [],
                'example' => ['users.read', 'documents.write'],
                'array' => true,
            ])
            ->addRule('secret', [
                'type' => self::TYPE_STRING,
                'description' => 'Secret key.',
                'example' => '919c2d18fb5d4...a2ae413da83346ad2',
            ])
        ;
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return 'Key';
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return Response::MODEL_KEY;
    }
}


    Hallo,

    Hierdie epos is vir jou gestuur omdat {{owner}} jou graag wou nooi om 'n spanlid te word van {{team}} by {{project}}.

    Om by die {{team}} span aan te sluit:

{{cta}}

    As jy nie belangstel nie, kan jy die boodskap ignoreer.

    Baie dankie,

    {{project}} span


package main

import (
    "fmt"
    "github.com/appwrite/sdk-for-go"
)

func main() {
    var client := appwrite.Client{}

    client.SetProject("5df5acd0d48c2") // Your project ID
    client.SetKey("919c2d18fb5d4...a2ae413da83346ad2") // Your secret API key

    var service := appwrite.Database{
        client: &client
    }

    var response, error := service.CreateDocument("[COLLECTION_ID]", , [], [], "[PARENT_DOCUMENT]", "", "assign")

    if error != nil {
        panic(error)
    }

    fmt.Println(response)
}


import 'package:appwrite/appwrite.dart';

void main() { // Init SDK
  Client client = Client();
  Account account = Account(client);

  client
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
  ;

  Future result = account.deleteSessions(  );

  result
    .then((response) {
      print(response);
    }).catchError((error) {
      print(error.response);
  });
}


keep keep keep add keep keep keep keep keep

<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;
use Utopia\Config\Config;

class Project extends Model
{
    public function __construct()
    {
        $this
            ->addRule('$id', [
                'type' => self::TYPE_STRING,
                'description' => 'Project ID.',
                'example' => '5e5ea5c16897e',
            ])
            ->addRule('name', [
                'type' => self::TYPE_STRING,
                'description' => 'Project name.',
                'default' => '',
                'example' => 'New Project',
            ])
            ->addRule('description', [
                'type' => self::TYPE_STRING,
                'description' => 'Project description.',
                'default' => '',
                'example' => 'This is a new project.',
            ])
            ->addRule('teamId', [
                'type' => self::TYPE_STRING,
                'description' => 'Project team ID.',
                'example' => '1592981250',
            ])
            ->addRule('logo', [
                'type' => self::TYPE_STRING,
                'description' => 'Project logo file ID.',
                'default' => '',
                'example' => '5f5c451b403cb',
            ])
            ->addRule('url', [
                'type' => self::TYPE_STRING,
                'description' => 'Project website URL.',
                'default' => '',
                'example' => '5f5c451b403cb',
            ])
            ->addRule('legalName', [
                'type' => self::TYPE_STRING,
                'description' => 'Company legal name.',
                'default' => '',
                'example' => 'Company LTD.',
            ])
            ->addRule('legalCountry', [
                'type' => self::TYPE_STRING,
                'description' => 'Country code in [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) two-character format.',
                'default' => '',
                'example' => 'US',
            ])
            ->addRule('legalState', [
                'type' => self::TYPE_STRING,
                'description' => 'State name.',
                'default' => '',
                'example' => 'New York',
            ])
            ->addRule('legalCity', [
                'type' => self::TYPE_STRING,
                'description' => 'City name.',
                'default' => '',
                'example' => 'New York City.',
            ])
            ->addRule('legalAddress', [
                'type' => self::TYPE_STRING,
                'description' => 'Company Address.',
                'default' => '',
                'example' => '620 Eighth Avenue, New York, NY 10018',
            ])
            ->addRule('legalTaxId', [
                'type' => self::TYPE_STRING,
                'description' => 'Company Tax ID.',
                'default' => '',
                'example' => '131102020',
            ])
            ->addRule('platforms', [
                'type' => Response::MODEL_PLATFORM,
                'description' => 'List of Platforms.',
                'default' => [],
                'example' => [],
                'array' => true,
            ])
            ->addRule('webhooks', [
                'type' => Response::MODEL_WEBHOOK,
                'description' => 'List of Webhooks.',
                'default' => [],
                'example' => [],
                'array' => true,
            ])
            ->addRule('keys', [
                'type' => Response::MODEL_KEY,
                'description' => 'List of API Keys.',
                'default' => [],
                'example' => [],
                'array' => true,
            ])
            ->addRule('domains', [
                'type' => Response::MODEL_DOMAIN,
                'description' => 'List of Domains.',
                'default' => [],
                'example' => [],
                'array' => true,
            ])
            ->addRule('tasks', [
                'type' => Response::MODEL_TASK,
                'description' => 'List of Tasks.',
                'default' => [],
                'example' => [],
                'array' => true,
            ])
        ;

        $providers = Config::getParam('providers', []);

        foreach ($providers as $index => $provider) {
            if (!$provider['enabled']) {
                continue;
            }

            $name = (isset($provider['name'])) ? $provider['name'] : 'Unknown';

            $this
                ->addRule('usersOauth2'.\ucfirst($index).'Appid', [
                    'type' => self::TYPE_STRING,
                    'description' => $name.' OAuth app ID.',
                    'example' => '123247283472834787438',
                    'default' => '',
                ])
                ->addRule('usersOauth2'.\ucfirst($index).'Secret', [
                    'type' => self::TYPE_STRING,
                    'description' => $name.' OAuth secret ID.',
                    'example' => 'djsgudsdsewe43434343dd34...',
                    'default' => '',
                ])
            ;
        }
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return 'Project';
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return Response::MODEL_PROJECT;
    }
}


const sdk = require('node-appwrite');

// Init SDK
let client = new sdk.Client();

let storage = new sdk.Storage(client);

client
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
    .setKey('919c2d18fb5d4...a2ae413da83346ad2') // Your secret API key
;

let promise = storage.getFile('[FILE_ID]');

promise.then(function (response) {
    console.log(response);
}, function (error) {
    console.log(error);
});


package main

import (
    "fmt"
    "github.com/appwrite/sdk-for-go"
)

func main() {
    var client := appwrite.Client{}

    client.SetProject("5df5acd0d48c2") // Your project ID
    client.SetKey("919c2d18fb5d4...a2ae413da83346ad2") // Your secret API key

    var service := appwrite.Health{
        client: &client
    }

    var response, error := service.GetDB()

    if error != nil {
        panic(error)
    }

    fmt.Println(response)
}


require 'appwrite'

client = Appwrite::Client.new()

client
    .set_endpoint('https://[HOSTNAME_OR_IP]/v1') # Your API Endpoint
    .set_project('5df5acd0d48c2') # Your project ID
    .set_key('919c2d18fb5d4...a2ae413da83346ad2') # Your secret API key
;

health = Appwrite::Health.new(client);

response = health.get_cache();

puts response


class Project extends Model
{
public function __construct()
{
$this


from appwrite.client import Client
from appwrite.services.health import Health

client = Client()

(client
  .set_endpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
  .set_project('5df5acd0d48c2') # Your project ID
  .set_key('919c2d18fb5d4...a2ae413da83346ad2') # Your secret API key
)

health = Health(client)

result = health.get_anti_virus()


let sdk = new Appwrite();

sdk
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
;

let promise = sdk.teams.getMemberships('[TEAM_ID]');

promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});


<?php

return [
    'AF' => 'Африка',
    'AN' => 'Антарктика',
    'AS' => 'Азия',
    'EU' => 'Европа',
    'NA' => 'Северная Америка',
    'OC' => 'Океания',
    'SA' => 'Южная Америка',
];


use Appwrite\Utopia\Response\Model;
class Task extends Model
{
public function __construct()
{
$this
->addRule('$id', [

<?php

namespace Appwrite\Utopia\Response\Model;

use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;

class BaseList extends Model
{
    /**
     * @var string
     */
    protected $name = '';

    /**
     * @var string
     */
    protected $type = '';

    public function __construct(string $name, string $type, string $key, string $model, bool $paging = true)
    {
        $this->name = $name;
        $this->type = $type;

        if ($paging) {
            $this->addRule('sum', [
                'type' => self::TYPE_INTEGER,
                'description' => 'Total sum of items in the list.',
                'example' => '5',
            ]);
        }
        $this->addRule($key, [
            'type' => $model,
            'description' => 'List of '.$key.'.',
            'example' => [],
            'array' => true,
        ]);
    }

    /**
     * Get Name
     *
     * @return string
     */
    public function getName():string
    {
        return $this->name;
    }

    /**
     * Get Collection
     *
     * @return string
     */
    public function getType():string
    {
        return $this->type;
    }
}