Compare commits

..
Author SHA1 Message Date
Matej Bačo 703a528d6d Catch OAuth duplication error 2022-07-25 10:21:24 +00:00
10381 changed files with 66392 additions and 233059 deletions
+3 -8
View File
@@ -56,8 +56,8 @@ _APP_SMTP_PORT=1025
_APP_SMTP_SECURE=
_APP_SMTP_USERNAME=
_APP_SMTP_PASSWORD=
_APP_SMS_PROVIDER=sms://username:password@mock
_APP_SMS_FROM=+123456789
_APP_PHONE_PROVIDER=phone://mock
_APP_PHONE_FROM=+123456789
_APP_STORAGE_LIMIT=30000000
_APP_STORAGE_PREVIEW_LIMIT=20000000
_APP_FUNCTIONS_SIZE_LIMIT=30000000
@@ -72,18 +72,13 @@ OPEN_RUNTIMES_NETWORK=appwrite_runtimes
_APP_EXECUTOR_SECRET=your-secret-key
_APP_EXECUTOR_HOST=http://appwrite-executor/v1
_APP_MAINTENANCE_INTERVAL=86400
_APP_MAINTENANCE_RETENTION_CACHE=2592000
_APP_MAINTENANCE_RETENTION_EXECUTION=1209600
_APP_MAINTENANCE_RETENTION_ABUSE=86400
_APP_MAINTENANCE_RETENTION_AUDIT=1209600
_APP_USAGE_AGGREGATION_INTERVAL=5
_APP_MAINTENANCE_RETENTION_USAGE_HOURLY=8640000
_APP_USAGE_AGGREGATION_INTERVAL=30
_APP_USAGE_STATS=enabled
_APP_LOGGING_PROVIDER=
_APP_LOGGING_CONFIG=
_APP_GRAPHQL_MAX_BATCH_SIZE=10
_APP_GRAPHQL_MAX_COMPLEXITY=250
_APP_GRAPHQL_MAX_DEPTH=3
DOCKERHUB_PULL_USERNAME=
DOCKERHUB_PULL_PASSWORD=
DOCKERHUB_PULL_EMAIL=
+24 -7
View File
@@ -1,7 +1,24 @@
app/config/** linguist-detectable=false
app/views/** linguist-detectable=false
app/controllers/** linguist-detectable=false
src/** linguist-detectable=false
tests/** linguist-detectable=false
public/scripts/** linguist-detectable=false
public/dist/scripts/** linguist-detectable=false
app/config/* linguist-detectable=false
app/config/*/* linguist-detectable=false
app/config/*/*/* linguist-detectable=false
app/config/*/*/*/* linguist-detectable=false
app/views/* linguist-detectable=false
app/views/*/* linguist-detectable=false
app/views/*/*/* linguist-detectable=false
app/views/*/*/*/* linguist-detectable=false
app/controllers/* linguist-detectable=false
app/controllers/*/* linguist-detectable=false
app/controllers/*/*/* linguist-detectable=false
app/controllers/*/*/*/* linguist-detectable=false
app/controllers/*/*/*/*/* linguist-detectable=false
src/* linguist-detectable=false
src/*/* linguist-detectable=false
src/*/*/* linguist-detectable=false
src/*/*/*/* linguist-detectable=false
src/*/*/*/*/* linguist-detectable=false
tests/* linguist-detectable=false
tests/*/* linguist-detectable=false
tests/*/*/* linguist-detectable=false
tests/*/*/*/* linguist-detectable=false
tests/*/*/*/*/* linguist-detectable=false
tests/*/*/*/*/*/* linguist-detectable=false
+87
View File
@@ -0,0 +1,87 @@
name: "🐛 Bug Report"
description: "Submit a bug report to help us improve"
title: "🐛 Bug Report: "
labels: [bug]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out our bug report form 🙏
- type: textarea
id: steps-to-reproduce
validations:
required: true
attributes:
label: "👟 Reproduction steps"
description: "How do you trigger this bug? Please walk us through it step by step."
placeholder: "When I ..."
- type: textarea
id: expected-behavior
validations:
required: true
attributes:
label: "👍 Expected behavior"
description: "What did you think would happen?"
placeholder: "It should ..."
- type: textarea
id: actual-behavior
validations:
required: true
attributes:
label: "👎 Actual Behavior"
description: "What did actually happen? Add screenshots, if applicable."
placeholder: "It actually ..."
- type: dropdown
id: appwrite-version
attributes:
label: "🎲 Appwrite version"
description: "What version of Appwrite are you running?"
options:
- Version 0.15.x
- Version 0.14.x
- Version 0.13.x
- Version 0.12.x
- Version 0.11.x
- Version 0.10.x
- Version 0.9.x
- Version 0.8.x
- Version 0.7.x
- Version 0.6.x
- Different version (specify in environment)
validations:
required: true
- type: dropdown
id: operating-system
attributes:
label: "💻 Operating system"
description: "What OS is your server / device running on?"
options:
- Linux
- MacOS
- Windows
- Something else
validations:
required: true
- type: textarea
id: environment
validations:
required: false
attributes:
label: "🧱 Your Environment"
description: "Is your environment customized in any way?"
placeholder: "I use Cloudflare for ..."
- type: checkboxes
id: no-duplicate-issues
attributes:
label: "👀 Have you spent some time to check if this issue has been raised before?"
description: "Have you Googled for a similar issue or checked our older issues for a similar bug?"
options:
- label: "I checked and didn't find similar issue"
required: true
- type: checkboxes
id: read-code-of-conduct
attributes:
label: "🏢 Have you read the Code of Conduct?"
options:
- label: "I have read the [Code of Conduct](https://github.com/appwrite/appwrite/blob/HEAD/CODE_OF_CONDUCT.md)"
required: true
+32
View File
@@ -0,0 +1,32 @@
name: "📚 Documentation"
description: "Report an issue related to documentation"
title: "📚 Documentation: "
labels: [documentation]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to make our documentation better 🙏
- type: textarea
id: issue-description
validations:
required: true
attributes:
label: "💭 Description"
description: "A clear and concise description of what the issue is."
placeholder: "Documentation should not ..."
- type: checkboxes
id: no-duplicate-issues
attributes:
label: "👀 Have you spent some time to check if this issue has been raised before?"
description: "Have you Googled for a similar issue or checked our older issues for a similar bug?"
options:
- label: "I checked and didn't find similar issue"
required: true
- type: checkboxes
id: read-code-of-conduct
attributes:
label: "🏢 Have you read the Code of Conduct?"
options:
- label: "I have read the [Code of Conduct](https://github.com/appwrite/appwrite/blob/HEAD/CODE_OF_CONDUCT.md)"
required: true
+40
View File
@@ -0,0 +1,40 @@
name: 🚀 Feature
description: "Submit a proposal for a new feature"
title: "🚀 Feature: "
labels: [feature]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out our feature request form 🙏
- type: textarea
id: feature-description
validations:
required: true
attributes:
label: "🔖 Feature description"
description: "A clear and concise description of what the feature is."
placeholder: "You should add ..."
- type: textarea
id: pitch
validations:
required: true
attributes:
label: "🎤 Pitch"
description: "Please explain why this feature should be implemented and how it would be used. Add examples, if applicable."
placeholder: "In my use-case, ..."
- type: checkboxes
id: no-duplicate-issues
attributes:
label: "👀 Have you spent some time to check if this issue has been raised before?"
description: "Have you Googled for a similar issue or checked our older issues for a similar bug?"
options:
- label: "I checked and didn't find similar issue"
required: true
- type: checkboxes
id: read-code-of-conduct
attributes:
label: "🏢 Have you read the Code of Conduct?"
options:
- label: "I have read the [Code of Conduct](https://github.com/appwrite/appwrite/blob/HEAD/CODE_OF_CONDUCT.md)"
required: true
+5 -6
View File
@@ -11,17 +11,16 @@ Happy contributing!
## What does this PR do?
(Provide a description of what this PR does and why it's needed.)
(Provide a description of what this PR does.)
## Test Plan
(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Screenshots may also be helpful.)
(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work.)
## Related PRs and Issues
- (Related PR or issue)
(If this PR is related to any other PR or resolves any issue or related to any issue link all related PR and issues here.)
## Checklist
### Have you read the [Contributing Guidelines on issues](https://github.com/appwrite/appwrite/blob/master/CONTRIBUTING.md)?
- [ ] Have you read the [Contributing Guidelines on issues](https://github.com/appwrite/appwrite/blob/master/CONTRIBUTING.md)?
- [ ] If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?
(Write your answer here.)
+4 -8
View File
@@ -1,9 +1,5 @@
name: "CodeQL"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
push:
branches: [master]
@@ -29,7 +25,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
@@ -42,14 +38,14 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
uses: github/codeql-action/autobuild@v1
# ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -63,4 +59,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
uses: github/codeql-action/analyze@v1
+19 -9
View File
@@ -1,24 +1,34 @@
name: "Linter"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [pull_request]
jobs:
lint:
tests:
name: Linter
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.0'
- name: Install dependencies
uses: php-actions/composer@v6
with:
php_version: '8.0'
args: --profile --ignore-platform-reqs
- name: Run Linter
run: |
docker run --rm -v $PWD:/app composer sh -c \
"composer install --profile --ignore-platform-reqs && composer lint"
run: ./vendor/bin/phpcs -p
-53
View File
@@ -1,53 +0,0 @@
name: "Release"
on:
release:
types: [published]
jobs:
tests:
name: Unit & E2E
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# Fetch submodules
submodules: recursive
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: appwrite/appwrite
tags: |
type=semver,pattern={{major}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}.{{minor}}.{{patch}}
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.meta.outputs.version }}
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+17 -29
View File
@@ -1,53 +1,34 @@
name: "Tests"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [pull_request]
jobs:
tests:
name: Unit & E2E
runs-on: ubuntu-latest
runs-on: self-hosted
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# Fetch submodules
submodules: recursive
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# This is a separate action that sets up buildx runner
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Build Appwrite
uses: docker/build-push-action@v3
with:
context: .
push: false
tags: appwrite-dev
load: true
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: |
DEBUG=false
TESTING=true
VERSION=dev
- name: Start Appwrite
# Upstream bug causes buildkit pulls to fail so prefetch base images
# https://github.com/moby/moby/issues/41864
run: |
echo "_APP_FUNCTIONS_RUNTIMES=php-8.0" >> .env
docker pull composer:2.0
docker pull php:8.0-cli-alpine
docker compose build --progress=plain
docker compose up -d
sleep 30
sleep 10
- name: Doctor
run: docker compose exec -T appwrite doctor
@@ -55,4 +36,11 @@ jobs:
run: docker compose exec -T appwrite vars
- name: Run Tests
run: docker compose exec -T appwrite test --debug
run: docker compose exec -T appwrite test --debug
- name: Teardown
if: always()
run: |
docker ps -aq | xargs docker rm --force || true
docker volume prune --force || true
docker network prune --force || true
-3
View File
@@ -5,11 +5,8 @@
/tests/resources/functions/**/code.tar.gz
/app/sdks/*
/.idea/
!/.idea/workspace.xml
!/.idea/php.xml
.DS_Store
.php_cs.cache
debug/
app/sdks
dev/yasd_init.php
.phpunit.result.cache
-4
View File
@@ -1,4 +0,0 @@
[submodule "app/console"]
path = app/console
url = https://github.com/appwrite/console
branch = 2.3.3
+1 -3
View File
@@ -1,9 +1,8 @@
tasks:
- name: Run Appwrite Docker Stack
init: |
git submodule update --init
docker compose build
docker compose pull
docker compose build
docker pull composer
command: |
docker run --rm --interactive --tty \
@@ -23,7 +22,6 @@ ports:
vscode:
extensions:
- ms-azuretools.vscode-docker
- zobo.php-intellisense
github:
# https://www.gitpod.io/docs/prebuilds#github-specific-configuration
-162
View File
@@ -1,165 +1,3 @@
# Version 1.3.1
## Bugs
- Fixed Migration issue regarding 500 error [4906](https://github.com/appwrite/appwrite/pull/5356)
# Version 1.3.0
## Features
- Password dictionary setting allows to compare user's password against command password database [4906](https://github.com/appwrite/appwrite/pull/4906)
- Password history setting allows to save user's last used password so that it may not be used again. Maximum number of history saved is 20, which can be configured. Minimum is 0 which means disabled. [#4866](https://github.com/appwrite/appwrite/pull/4866)
- Update APIs to check X-Appwrite-Timestamp header [#5024](https://github.com/appwrite/appwrite/pull/5024)
- Database relationships [#5238](https://github.com/appwrite/appwrite/pull/5238)
- New query operators [#5238](https://github.com/appwrite/appwrite/pull/5238)
- Team preferences [#5196](https://github.com/appwrite/appwrite/pull/5196)
- Update attribute metadata [#5164](https://github.com/appwrite/appwrite/pull/5164)
## Bugs
- Fix not storing function's response on response codes 5xx [#4610](https://github.com/appwrite/appwrite/pull/4610)
- Fix expire to formatTz in create account session [#4985](https://github.com/appwrite/appwrite/pull/4985)
- Fix deleting projects when organization is deleted [#5335](https://github.com/appwrite/appwrite/pull/5335)
- Fix deleting collections from a project [#4983](https://github.com/appwrite/appwrite/pull/4983)
- Fix cleaning up project databases [#4984](https://github.com/appwrite/appwrite/pull/4984)
- Fix creating documents with attributes with special characters [#246](https://github.com/utopia-php/database/pull/246)
- Fix deleting attribute not deleting metadata index [#246](https://github.com/utopia-php/database/pull/246)
- Fix create attribute event payload [#246](https://github.com/utopia-php/database/pull/246)
# Version 1.2.1
## Changes
- Upgrade Console to [2.2.0](https://github.com/appwrite/console/releases/tag/2.2.0)
- Update DBIP Database [#5049](https://github.com/appwrite/appwrite/pull/5049)
## Bugs
- Fix a few null safety warnings [#4654](https://github.com/appwrite/appwrite/pull/4654)
- Fix timestamp format in Realtime response [#4515](https://github.com/appwrite/appwrite/pull/4515)
- Add flutter-web as a platform type [#4992](https://github.com/appwrite/appwrite/pull/4992)
- Fix typo in Model/Locale.php [#4669](https://github.com/appwrite/appwrite/pull/4669)
- Fix deletes worker not deleting project database tables [#4984](https://github.com/appwrite/appwrite/pull/4984)
- Fix deletes worker not deleting database collections [#4983](https://github.com/appwrite/appwrite/pull/4983)
- Fix restart policy for worker-messaging container [#4994](https://github.com/appwrite/appwrite/pull/4994)
- Fix validating origin for apple platforms [#5089](https://github.com/appwrite/appwrite/pull/5089)
# Version 1.2.0
## Features
- Added GraphQL API [#974](https://github.com/appwrite/appwrite/pull/974)
- Added GraphQL Explorer [#974](https://github.com/appwrite/appwrite/pull/974)
- Added ability to set max sessions per user per project [#4831](https://github.com/appwrite/appwrite/pull/4831)
## Changes
- Get default region from environment on project create [#4780](https://github.com/appwrite/appwrite/pull/4780)
- Fix french translation [#4782](https://github.com/appwrite/appwrite/pull/4782)
- Fix max mimetype size [#4814](https://github.com/appwrite/appwrite/pull/4814)
## Bugs
- Fix invited account verified status [#4776](https://github.com/appwrite/appwrite/pull/4776)
# Version 1.1.2
## Changes
- Released `appwrite/console` [2.0.2](https://github.com/appwrite/console/releases/tag/2.0.2)
- Make `region` parameter optional with default for project create [#4763](https://github.com/appwrite/appwrite/pull/4763)
## Bugs
- Fix default oauth paths [#4725](https://github.com/appwrite/appwrite/pull/4725)
- Fix session expiration, and expired session deletion [#4739](https://github.com/appwrite/appwrite/pull/4739)
- Fix processing status on sync executions [#4737](https://github.com/appwrite/appwrite/pull/4737)
- Fix Locale API returning Unknown continent [#4761](https://github.com/appwrite/appwrite/pull/4761)
# Version 1.1.1
## Bugs
- Fix Deletes worker using incorrect device for file deletion [#4662](https://github.com/appwrite/appwrite/pull/4662)
- Fix Migration for Stats adding the region attribute [#4704](https://github.com/appwrite/appwrite/pull/4704)
- Fix Migration stopping scheduled functions [#4704](https://github.com/appwrite/appwrite/pull/4704)
- Fix Migration enabling OAuth providers with data by default [#4704](https://github.com/appwrite/appwrite/pull/4704)
- Fix Error pages when OAuth providers are disabled [#4704](https://github.com/appwrite/appwrite/pull/4704)
# Version 1.1.0
## Features
- Added support for the new Appwrite Console [#4655](https://github.com/appwrite/appwrite/pull/4655)
- Added new property to projects configuration: `authDuration` which allows you to alter the duration of signed in sessions for your project. [#4618](https://github.com/appwrite/appwrite/pull/4618)
## Bugs
- Fix license detection for Flutter and Dart SDKs [#4435](https://github.com/appwrite/appwrite/pull/4435)
- Fix missing realtime event for create function deployment [#4574](https://github.com/appwrite/appwrite/pull/4574)
- Fix missing `status`, `buildStderr` and `buildStderr` from get deployment response [#4611](https://github.com/appwrite/appwrite/pull/4611)
- Fix project pagination in DB usage aggregation [#4517](https://github.com/appwrite/appwrite/pull/4517)
- Fix missing file permissions due to cache [#4661](https://github.com/appwrite/appwrite/pull/4661)
- Fix usage stats for async function executions [#4674](https://github.com/appwrite/appwrite/pull/4674)
# Version 1.0.3
## Bugs
- Fix document audit deletion [#4429](https://github.com/appwrite/appwrite/pull/4429)
- Fix attribute and index deletion when deleting a collection [#4429](https://github.com/appwrite/appwrite/pull/4429)
# Version 1.0.2
## Bugs
- Fixed nullable values in functions variables [#3885](https://github.com/appwrite/appwrite/pull/3885)
- Fixed migration for audit by migrating the `time` attribute [#4038](https://github.com/appwrite/appwrite/pull/4038)
- Fixed default value for creating Boolean Attribute [#4040](https://github.com/appwrite/appwrite/pull/4040)
- Fixed phone authentication code to be hashed in the internal database [#3906](https://github.com/appwrite/appwrite/pull/3906)
- Fixed `/v1/teams/:teamId/memberships/:membershipId` response [#3883](https://github.com/appwrite/appwrite/pull/3883)
- Fixed removing variables when function is deleted [#3884](https://github.com/appwrite/appwrite/pull/3884)
- Fixed scheduled function not being triggered [#3908](https://github.com/appwrite/appwrite/pull/3908)
- Fixed Phone Provider configuration [#3862](https://github.com/appwrite/appwrite/pull/3883)
- Fixed Queries with `0` values [utopia-php/database#194](https://github.com/utopia-php/database/pull/194)
# Version 1.0.1
## Bugs
- Fixed migration for abuse by migrating the `time` attribute [#3839](https://github.com/appwrite/appwrite/pull/3839)
# Version 1.0.0
## BREAKING CHANGES
- All Date values are now stored as ISO-8601 instead of UNIX timestamps [#3516](https://github.com/appwrite/appwrite/pull/3516)
- Permission levels and syntax have been reworked. See the Permissions V2 section in the document for more information [#3700](https://github.com/appwrite/appwrite/pull/3700)
- Function Variables are now stored in a separate collection with their own API endpoints [#3634](https://github.com/appwrite/appwrite/pull/3634)
- Resources that are computed asynchronously, such as function deployments, will now return a `202 Accepted` status code instead of `200 OK` [#3547](https://github.com/appwrite/appwrite/pull/3547)
- Queries have been improved to allow even more flexibility, and introduced to new endpoints. See the Queries V2 section in the document for more information [#3702](https://github.com/appwrite/appwrite/pull/3702)
- Compound indexes are now more flexible [#151](https://github.com/utopia-php/database/pull/151)
- `createExecution` parameter `async` default value was changed from `true` to `false` [#3781](https://github.com/appwrite/appwrite/pull/3781)
- String attribute `status` has been refactored to a Boolean attribute `enabled` in the functions collection [#3798](https://github.com/appwrite/appwrite/pull/3798)
- `time` attribute in Execution response model has been renamed to `duration` to be more consistent with other response models. [#3801](https://github.com/appwrite/appwrite/pull/3801)
- Renamed the following list endpoints to stay consistent with other endpoints [#3825](https://github.com/appwrite/appwrite/pull/3825)
- `getMemberships` to `listMemberships` in Teams API
- `getMemberships` to `listMemberships` in Users API
- `getLogs` to `listLogs` in Users API
- `getLogs` to `listLogs` in Accounts API
- `getSessions` to `listSessions` in Accounts API
- `getSessions` to `listSessions` in Users API
- `getCountries` to `listCountries` in Locale API
- `getCountriesEU` to `listCountriesEU` in Locale API
- `getCountriesPhones` to `listCountriesPhones` in Locale API
- `getContinents` to `listContinents` in Locale API
- `getCurrencies` to `listCurrencies` in Locale API
- `getLanguages` to `listLanguages` in Locale API
## Features
- Added the UI to see the Parent ID of all resources within the UI. [#3653](https://github.com/appwrite/appwrite/pull/3653)
- Added automatic cache cleaning for internal Appwrite services [#3491](https://github.com/appwrite/appwrite/pull/3491)
- Added the ability for Appwrite to handle importing hashed passwords, this can be leveraged to import existing user data from other systems. More information can be found in the document linked above. [#2747](https://github.com/appwrite/appwrite/pull/2747)
- `Users` has now been renamed to `Authentication` within the Appwrite console [#3664](https://github.com/appwrite/appwrite/pull/3664)
- More endpoints were made public (for guests) with proper rate limits [#3741](https://github.com/appwrite/appwrite/pull/3741)
- Added Disqus, Podio, and Etsy OAuth providers [#3526](https://github.com/appwrite/appwrite/pull/3526), [#3488](https://github.com/appwrite/appwrite/pull/3488), [#3522](https://github.com/appwrite/appwrite/pull/3522)
- Function logs now capture stdout [#3656](https://github.com/appwrite/appwrite/pull/3656)
- Added the ability to grant guests write permissions for documents, files and executions [#3727](https://github.com/appwrite/appwrite/pull/3727)
## Bugs
- Fixed an issue where after resetting your password in the Appwrite console, you would not be redirected to the login page. [#3654](https://github.com/appwrite/appwrite/pull/3654)
- Fixed an issue where invalid data could be loaded into the Appwrite console. [#3660](https://github.com/appwrite/appwrite/pull/3660)
- Fixed an issue where users using the MySQL adapter for Appwrite would run into an issue with full text indexes [#154](https://github.com/utopia-php/database/pull/154)
- Fix teams being created with no owners [#3558](https://github.com/appwrite/appwrite/pull/3558)
- Fixed a bug where you could not search users by phone [#3619](https://github.com/appwrite/appwrite/pull/3619)
- Fixed a bug where unaccepted invitations would grant access to projects [#3738](https://github.com/appwrite/appwrite/pull/3738)
# Version 0.15.3
## Features
- Added hint during Installation for DNS Configuration by @PineappleIOnic in https://github.com/appwrite/appwrite/pull/2450
## Bugs
- Fixed Migration for Attributes and Indexes by @TorstenDittmann in https://github.com/appwrite/appwrite/pull/3568
- Fixed Closed Icon in the alerts to be centered by @TorstenDittmann in https://github.com/appwrite/appwrite/pull/3594
- Fixed Response Model for Get and Update Database Endpoint by @ishanvyas22 in https://github.com/appwrite/appwrite/pull/3553
- Fixed Missing Usage on Functions exection by @Meldiron in https://github.com/appwrite/appwrite/pull/3543
- Fixed Validation for Permissions to only accept a maximum of 100 Permissions for all endpoints by @Meldiron in https://github.com/appwrite/appwrite/pull/3532
- Fixed backwards compatibility for Create Email Session Endpoint by @stnguyen90 in https://github.com/appwrite/appwrite/pull/3517
# Version 0.15.2
## Bugs
- Fixed Realtime Authentication for the Console by @TorstenDittmann in https://github.com/appwrite/appwrite/pull/3506
+76
View File
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity, expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at team@appwrite.io. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
+71 -87
View File
@@ -1,14 +1,14 @@
# Contributing
We would ❤️ you to contribute to Appwrite and help make it better! We want contributing to Appwrite to be fun, enjoyable, and educational for anyone and everyone. All contributions are welcome, including issues, and new docs, as well as updates and tweaks, blog posts, workshops, and more.
We would ❤️ for you to contribute to Appwrite and help make it better! We want contributing to Appwrite to be fun, enjoyable, and educational for anyone and everyone. All contributions are welcome, including issues, new docs as well as updates and tweaks, blog posts, workshops, and more.
## How to Start?
If you are worried or dont know where to start, check out the next section that explains what kind of help we could use and where you can get involved. You can send your questions to [@appwrite](https://twitter.com/appwrite) on Twitter or to anyone from the [Appwrite team on Discord](https://appwrite.io/discord). You can also submit an issue, and a maintainer can guide you!
If you are worried or dont know where to start, check out our next section explaining what kind of help we could use and where can you get involved. You can reach out with questions to [Eldad Fux (@eldadfux)](https://twitter.com/eldadfux) or [@appwrite](https://twitter.com/appwrite) on Twitter, and anyone from the [Appwrite team on Discord](https://discord.gg/GSeTUeA). You can also submit an issue, and a maintainer can guide you!
## Code of Conduct
Help us keep Appwrite open and inclusive. Please read and follow our [Code of Conduct](https://github.com/appwrite/.github/blob/main/CODE_OF_CONDUCT.md).
Help us keep Appwrite open and inclusive. Please read and follow our [Code of Conduct](/CODE_OF_CONDUCT.md).
## Submit a Pull Request 🚀
@@ -24,13 +24,13 @@ doc-548-submit-a-pull-request-section-to-contribution-guide
When `TYPE` can be:
- **feat** - a new feature
- **feat** - is a new feature
- **doc** - documentation only changes
- **cicd** - changes related to CI/CD system
- **fix** - a bug fix
- **refactor** - code change that neither fixes a bug nor adds a feature
**All PRs must include a commit message with the description of the changes made!**
**All PRs must include a commit message with the changes description!**
For the initial start, fork the project and use git clone command to download the repository to your computer. A standard procedure for working on an issue would be to:
@@ -40,33 +40,33 @@ For the initial start, fork the project and use git clone command to do
$ git pull
```
2. Create a new branch from `master` like: `doc-548-submit-a-pull-request-section-to-contribution-guide`.<br/>
2. Create new branch from `master` like: `doc-548-submit-a-pull-request-section-to-contribution-guide`<br/>
```
$ git checkout -b [name_of_your_new_branch]
```
3. Work - commit - repeat (make sure you're on the correct branch!)
3. Work - commit - repeat ( be sure to be in your branch )
4. Before you push your changes, make sure your code follows the `PSR12` coding standards, which is the standard that Appwrite currently follows. You can easily do this by running the formatter.
4. Before you push your changes, make sure your code follows the `PSR12` coding standards , which is the standard Appwrite follows currently. You can easily do this by running the formatter.
```bash
composer format <your file path>
```
Now, go a step further by running the linter using the following command to manually fix the issues the formatter wasn't able to.
Now, go a step further by running the linter by the following command to manually fix the issues the formatter wasn't able to fix.
```bash
composer lint <your file path>
```
This will give you a list of errors to rectify. If you need more information on the errors, you can pass in additional command line arguments to get more verbose information. More lists of available arguments can be found [here](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Usage). A very useful command line argument is `--report=diff`. This will give you the expected changes by the linter for easy fixing of formatting issues.
This will give you a list of errors for you to rectify , if there is an instance you need more information on the errors being displayed you can pass in additional command line arguments. More list of available arguments can be found [here](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Usage). A very useful command line argument is `--report=diff`. This will give you the expected changes by the linter for easy fixing of formatting issues.
```bash
composer lint --report=diff <your file path>
```
5. Push changes to GitHub.
5. Push changes to GitHub
```
$ git push origin [name_of_your_new_branch]
@@ -76,24 +76,23 @@ $ git push origin [name_of_your_new_branch]
If you go to your repository on GitHub, you'll see a `Compare & pull request` button. Click on that button.
7. Start a Pull Request
Now submit the pull request and click on `Create pull request`.
8. Get a code review approval/reject.
9. After approval, merge your PR.
8. Get a code review approval/reject
9. After approval, merge your PR
10. GitHub will automatically delete the branch after the merge is done. (they can still be restored).
## Setup From Source
To set up a working **development environment**, just fork the project git repository and install the backend and frontend dependencies using the proper package manager and create run the docker-compose stack.
> If you just want to install Appwrite for day-to-day use and not as a contributor, you can reference the [installation guide](https://github.com/appwrite/appwrite#installation), the [getting started guide](https://appwrite.io/docs/getting-started-for-web), or the main [README](README.md) file.
> If you just want to install Appwrite for day-to-day usage and not as a code maintainer use this [installation guide](https://github.com/appwrite/appwrite#installation).
Please note that these instructions are for setting a functional dev environment. If you want to set up an Appwrite instance to integrate into your app, you should probably try and install Appwrite by using the instructions in the [getting started guide](https://appwrite.io/docs/getting-started-for-web) or in the main [README](README.md) file.
```bash
git clone git@github.com:[YOUR_FORK_HERE]/appwrite.git
cd appwrite
git submodule update --init
docker compose build
docker compose up -d
```
@@ -117,7 +116,7 @@ After finishing the installation process, you can start writing and editing code
#### Advanced Topics
We love to create issues that are good for beginners and label them as `good first issue` or `hacktoberfest`, but some more advanced topics might require extra knowledge. Below is a list of links you can use to learn about the more advanced topics that will help you master the Appwrite codebase.
We love to create issues that are good for beginners and label them as `good first issue` or `hacktoberfest`, but some more advanced topics might require extra knowledge. Below is a list of links you can use to learn more about some of the more advance topics that will help you master the Appwrite codebase.
##### Tools and Libs
@@ -143,14 +142,14 @@ Learn more at our [Technology Stack](#technology-stack) section.
##### Security
- [Appwrite Auth and ACL](https://github.com/appwrite/appwrite/blob/master/docs/specs/authentication.drawio.svg)
- [Appwrite Auth and ACL](https://github.com/appwrite/appwrite/blob/0.7.x/docs/specs/authentication.drawio.svg)
- [OAuth](https://en.wikipedia.org/wiki/OAuth)
- [Encryption](https://medium.com/searchencrypt/what-is-encryption-how-does-it-work-e8f20e340537#:~:text=Encryption%20is%20a%20process%20that,%2C%20or%20decrypt%2C%20the%20information.)
- [Hashing](https://searchsqlserver.techtarget.com/definition/hashing#:~:text=Hashing%20is%20the%20transformation%20of,it%20using%20the%20original%20value.)
## Architecture
Appwrite's current structure is a combination of both [Monolithic](https://en.wikipedia.org/wiki/Monolithic_application) and [Microservice](https://en.wikipedia.org/wiki/Microservices) architectures.
Appwrite's current structure is a combination of both [Monolithic](https://en.wikipedia.org/wiki/Monolithic_application) and [Microservice](https://en.wikipedia.org/wiki/Microservices) architectures, but our final goal, as we grow, is to be using only microservices.
---
@@ -188,23 +187,20 @@ Appwrite's current structure is a combination of both [Monolithic](https://en.wi
├── src # Supporting libraries (each lib has one role, common libs are released as individual projects)
│ └── Appwrite
│ ├── Auth
│ ├── Database
│ ├── Detector
│ ├── Docker
| ├── DSN
│ ├── Event
│ ├── Extend
│ ├── GraphQL
│ ├── Messaging
│ ├── Migration
│ ├── Network
│ ├── OpenSSL
│ ├── Promises
│ ├── Realtime
│ ├── Resque
│ ├── Specification
│ ├── Task
│ ├── Template
│ ├── URL
│ ├── Usage
│ └── Utopia
└── tests # End to end & unit tests
├── e2e
@@ -216,13 +212,13 @@ Appwrite's current structure is a combination of both [Monolithic](https://en.wi
Appwrite's main API container is designed as a monolithic app. This is a decision we made to allow us to develop the project faster while still being a very small team.
Although the Appwrite API is a monolithic app, it has a very clear separation of concern as each internal service or worker is separated by its container, which allows us to start breaking services for better maintenance and scalability as we grow.
Although the Appwrite API is a monolithic app, it has a very clear separation of concern as each internal service or worker is separated by its container, which will allow us as we grow to start breaking services for better maintenance and scalability.
### The Microservice Part
Each container in Appwrite is a microservice on its own. Each service is an independent process that can scale without regard to any of the other services.
Currently, all the Appwrite microservices are intended to communicate using the TCP protocol over a private network. With the exception of the public-facing port 80 and 443, which by default are used to expose the Appwrite HTTP API, you should **avoid exposing any other services' ports**.
Currently, all of the Appwrite microservices are intended to communicate using the TCP protocol over a private network. You should be aware to not expose any of the services to the public-facing network, besides the public port 80 and 443, who, by default, are used to expose the Appwrite HTTP API.
## Ports
@@ -230,43 +226,43 @@ Appwrite dev version uses ports 80 and 443 as an entry point to the Appwrite API
## Technology Stack
To start helping us to improve the Appwrite server by submitting code, prior knowledge of Appwrite's technology stack can help you get started.
To start helping us to improve the Appwrite server by submitting code, prior knowledge of Appwrite's technology stack can help you with getting started.
Appwrite stack is a combination of a variety of open-source technologies and tools. Appwrite backend API is written primarily with PHP version 7 and above, on top of the [Utopia PHP framework](https://github.com/utopia-php/framework). The Appwrite frontend is built with tools like gulp, less, and [litespeed.js](https://github.com/litespeed-js). We use Docker as the container technology to package the Appwrite server for easy on-cloud, on-premise, or on-localhost integration.
Appwrite stack is combined from a variety of open-source technologies and tools. Appwrite backend API is written primarily with PHP version 7 and above on top of the [Utopia PHP framework](https://github.com/utopia-php/framework). The Appwrite frontend is built with tools like gulp, less, and [litespeed.js](https://github.com/litespeed-js). We use Docker as the container technology to package the Appwrite server for easy integration on-cloud, on-premise, or on-localhosts.
### Other Technologies
- Redis - for managing cache and in-memory data (currently, we do not use Redis for persistent data).
- MariaDB - for database storage and queries.
- InfluxDB - for managing stats and time-series based data.
- Statsd - for sending data over UDP protocol (using Telegraf).
- ClamAV - for validating and scanning storage files.
- Redis - for managing cache and in-memory data (currently, we do not use Redis for persistent data)
- MariaDB - for database storage and queries
- InfluxDB - for managing stats and time-series based data
- Statsd - for sending data over UDP protocol (using Telegraf)
- ClamAV - for validating and scanning storage files
- Imagemagick - for manipulating and managing image media files.
- Webp - for better compression of images on supporting clients.
- SMTP - for sending email messages and alerts.
- Resque - for managing data queues and scheduled tasks over a Redis server.
- Webp - for better compression of images on supporting clients
- SMTP - for sending email messages and alerts
- Resque - for managing data queues and scheduled tasks over a Redis server
## Package Managers
Appwrite uses a package manager for managing code dependencies for both backend and frontend development. We try our best to avoid creating any unnecessary dependencies. New dependency to the project is subjected to a lead developer's review and approval.
Appwrite uses a package manager for managing code dependencies for both backend and frontend development. We try our best to avoid creating any unnecessary, and any new dependency to the project is subjected to a lead developer review and approval.
Many of Appwrite's internal modules are also used as dependencies to allow other Appwrite projects to reuse them and as a way to contribute back to the community.
Many of Appwrite's internal modules are also used as dependencies to allow other Appwrite's projects to reuse them and as a way to contribute them back to the community.
Appwrite uses [PHP's Composer](https://getcomposer.org/) for managing dependencies on the server-side and [JS NPM](https://www.npmjs.com/) for managing dependencies on the frontend side.
## Coding Standards
Appwrite follows the [PHP-FIG standards](https://www.php-fig.org/). Currently, we use both PSR-0 and PSR-12 for coding standards and autoloading standards.
Appwrite is following the [PHP-FIG standards](https://www.php-fig.org/). Currently, we are using both PSR-0 and PSR-12 for coding standards and autoloading standards.
We use prettier for our JS coding standards and auto-formatting for our code.
We use prettier for our JS coding standards and auto-formatting our code.
## Scalability, Speed, and Performance
Appwrite is built to scale. Please keep in mind that the Appwrite stack can run in different environments and different scales.
We intend Appwrite to be as easy to set up as possible in a single localhost, and to grow easily into a large environment with dozens and even hundreds of instances.
We wish Appwrite will be as easy to set up and in a single, localhost, and easy to grow to a large environment with dozens and even hundreds of instances.
When contributing code, please take into account the following:
When contributing code, please take into account the following considerations:
- Response Time
- Throughput
@@ -277,25 +273,25 @@ When contributing code, please take into account the following:
- Background Jobs
- Task Execution Time
## Security and Privacy
## Security & Privacy
Security and privacy are extremely important to Appwrite, developers, and users alike. Make sure to follow the best industry standards and practices.
## Dependencies
Please avoid introducing new dependencies to Appwrite without consulting the team. New dependencies can be very helpful, but they also introduce new security and privacy risks, add complexity, and impact the total docker image size.
Please avoid introducing new dependencies to Appwrite without consulting the team. New dependencies can be very helpful but also introduce new security and privacy issues, complexity, and impact total docker image size.
Adding a new dependency should have vital value for the product with minimum possible risk.
Adding a new dependency should have vital value on the product with minimum possible risk.
## Introducing New Features
We would 💖 you to contribute to Appwrite, but we also want to ensure Appwrite is loyal to its vision and mission statement 🙏.
We would 💖 you to contribute to Appwrite, but we would also like to make sure Appwrite is as great as possible and loyal to its vision and mission statement 🙏.
For us to find the right balance, please open an issue explaining your ideas before introducing a new pull request.
This will allow the Appwrite community to sufficiently discuss the new feature value and how it fits within the product roadmap and vision.
This will allow the Appwrite community to have sufficient discussion about the new feature value and how it fits in the product roadmap and vision.
This is also important for the Appwrite lead developers to be able to provide technical input and potentially a different emphasis regarding the feature design and architecture. Some bigger features might need to go through our [RFC process](https://github.com/appwrite/rfc).
This is also important for the Appwrite lead developers to be able to give technical input and different emphasis regarding the feature design and architecture. Some bigger features might need to go through our [RFC process](https://github.com/appwrite/rfc).
## Build
@@ -319,34 +315,30 @@ The Runtimes for all supported cloud functions (multicore builds) can be found a
## Generate SDK
The following steps are used to generate a new console SDK:
For generating a new console SDK follow the next steps:
1. Update the console spec file located at `app/config/specs/swagger2-<version-number>.console.json` using Appwrite Tasks. Run the `php app/cli.php specs <version-number> normal` command in a running `appwrite/appwrite` container.
2. Generate a new SDK using the command `php app/cli.php sdks`.
3. Change your working dir using `cd app/sdks/console-web`.
4. Build the new SDK `npm run build`.
5. Copy `iife/sdk.js` to `appwrite.js`.
6. Go back to the root of the project `run npm run build`.
2. Generate a new SDK using the command `php app/cli.php sdks`
3. Change your working dir using `cd app/sdks/console-web`
4. Build the new SDK `npm run build`
5. Copy `iife/sdk.js` to `appwrite.js`
6. Go back to the root of the project `run npm run build`
## Checklist for Releasing SDKs
Things to remember when releasing SDKs:
Things to remember when releasing SDKs
- Update the Changelogs in **docs/sdks** (right now only Dart and Flutter are using these).
- Update **GETTING_STARTED.md** in **docs/sdks** for each SDKs if any changes in the related APIs are in there.
- Update SDK versions as required on **app/config/platforms.php**.
- Generate SDKs using the command `php app/cli.php sdks` and follow the instructions.
- Release new tags on GitHub repository for each SDK.
- Update the Changelogs in **docs/sdks** (right now only Dart and Flutter are using these)
- Update **GETTING_STARTED.md** in **docs/sdks** for each SDKs if any changes in the related APIs in there
- Update SDK versions as required on **app/config/platforms.php**
- Generate SDKs using the command `php app/cli.php sdks` and follow the instructions
- Release new tags on GitHub repository for each SDKs
## Debug
Appwrite uses [yasd](https://github.com/swoole/yasd) debugger, which can be made available during build of Appwrite. You can connect to the debugger using VS Code's [PHP Debug](https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug) extension.
Appwrite uses [yasd](https://github.com/swoole/yasd) debugger, which can be made available during build of Appwrite. You can connect to the debugger using VS Code [PHP Debug](https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug) extension or if you are in PHP Storm you don't need any plugin. Below are the settings required for remote debugger connection.
If you are in PHP Storm you don't need any plugin. Below are the settings required for remote debugger connection:
1. Create an init file.
2. Duplicate **dev/yasd_init.php.stub** file and name it **dev/yasd_init.php**.
3. Set **DEBUG** build arg in **appwrite** service in **docker-compose.yml** file.
First, you need to create an init file. Duplicate **dev/yasd_init.php.stub** file and name it **dev/yasd_init.php** and there change the IP address to your development machine's IP. Without the proper IP address debugger wont connect. And you also need to set **DEBUG** build arg in **appwrite** service in **docker-compose.yml** file.
### VS Code Launch Configuration
@@ -364,7 +356,7 @@ If you are in PHP Storm you don't need any plugin. Below are the settings requir
### PHPStorm Setup
In settings, go to **Languages & Frameworks** > **PHP** > **Debug**, under **Xdebug** set the debug port to **9005** and enable the **can accept external connections** checkbox.
In settings, go to **Languages & Frameworks** > **PHP** > **Debug**, there under **Xdebug** set the debug port to **9005** and enable **can accept external connections** checkbox.
## Tests
@@ -386,7 +378,7 @@ To run end-2-end tests use:
docker compose exec appwrite test /usr/src/code/tests/e2e
```
To run end-2-end tests for a specific service use:
To run end-2-end tests for a spcific service use:
```bash
docker compose exec appwrite test /usr/src/code/tests/e2e/Services/[ServiceName]
@@ -435,47 +427,39 @@ composer lint
composer lint <your file path>
```
## Clearing the Cache
If you need to clear the cache, you can do so by running the following command:
```bash
docker compose exec redis redis-cli FLUSHALL
```
## Tutorials
From time to time, our team will add tutorials that will help contributors find their way in the Appwrite source code. Below is a list of currently available tutorials:
- [Adding Support for a New OAuth2 Provider](./docs/tutorials/add-oauth2-provider.md)
- [Appwrite Environment Variables](./docs/tutorials/add-environment-variable.md)
- [Running in Production](https://appwrite.io/docs/production)
- [Appwrite Environment Variables](./docs/tutorials/environment-variables.md)
- [Running in Production](./docs/tutorials/running-in-production.md)
- [Adding Storage Adapter](./docs/tutorials/add-storage-adapter.md)
## Other Ways to Help
Pull requests are great, but there are many other ways you can help Appwrite.
Pull requests are great, but there are many other areas where you can help Appwrite.
### Blogging & Speaking
Blogging, speaking about, or creating tutorials about one of Appwrites many features are great ways to get the word out about Appwrite. Mention [@appwrite](https://twitter.com/appwrite) on Twitter and/or [email team@appwrite.io](mailto:team@appwrite.io) so we can give pointers and tips and help you spread the word by promoting your content on the different Appwrite communication channels. Please add your blog posts and videos of talks to our [Awesome Appwrite](https://github.com/appwrite/awesome-appwrite) repo on GitHub.
Blogging, speaking about, or creating tutorials about one of Appwrites many features. Mention [@appwrite](https://twitter.com/appwrite) on Twitter and/or [email team@appwrite.io](mailto:team@appwrite.io) so we can give pointers and tips and help you spread the word by promoting your content on the different Appwrite communication channels. Please add your blog posts and videos of talks to our [Awesome Appwrite](https://github.com/appwrite/awesome-appwrite) repo on GitHub.
### Presenting at Meetups
We encourage our contributors to present at meetups and conferences about your Appwrite projects. Your unique challenges and successes in building things with Appwrite can provide great speaking material. Wed love to review your talk abstract/CFP, so get in touch with us if youd like some help!
Presenting at meetups and conferences about your Appwrite projects. Your unique challenges and successes in building things with Appwrite can provide great speaking material. Wed love to review your talk abstract/CFP, so get in touch with us if youd like some help!
### Sending Feedbacks and Reporting Bugs
### Sending Feedbacks & Reporting Bugs
Sending feedback is a great way for us to understand your different use cases of Appwrite better. If you had any issues, bugs, or want to share your experience, feel free to do so on our GitHub issues page or at our [Discord channel](https://discord.gg/GSeTUeA).
Sending feedback is a great way for us to understand your different use cases of Appwrite better. If you had any issues, bugs, or want to share about your experience, feel free to do so on our GitHub issues page or at our [Discord channel](https://discord.gg/GSeTUeA).
### Submitting New Ideas
If you think Appwrite could use a new feature, please open an issue on our GitHub repository, stating as much information as you have about your new idea and its implications. We would also use this issue to gather more information, get more feedback from the community, and have a proper discussion about the new feature.
If you think Appwrite could use a new feature, please open an issue on our GitHub repository, stating as much information as you can think about your new idea and it's implications. We would also use this issue to gather more information, get more feedback from the community, and have a proper discussion about the new feature.
### Improving Documentation
Submitting documentation updates, enhancements, designs, or bug fixes, as well as spelling or grammar fixes is much appreciated.
Submitting documentation updates, enhancements, designs, or bug fixes. Spelling or grammar fixes will be very much appreciated.
### Helping Someone
Consider searching for Appwrite on Discord, GitHub, or StackOverflow to help someone who needs help. You can also help by teaching others how to contribute to Appwrite's repo!
Searching for Appwrite on Discord, GitHub, or StackOverflow and helping someone else who needs help. You can also help by teaching others how to contribute to Appwrite's repo!
+156 -19
View File
@@ -12,24 +12,118 @@ RUN composer install --ignore-platform-reqs --optimize-autoloader \
--no-plugins --no-scripts --prefer-dist \
`if [ "$TESTING" != "true" ]; then echo "--no-dev"; fi`
FROM --platform=$BUILDPLATFORM node:16.14.2-alpine3.15 as node
FROM node:16.14.2-alpine3.15 as node
COPY app/console /usr/local/src/console
WORKDIR /usr/local/src/
WORKDIR /usr/local/src/console
ARG VITE_GA_PROJECT
ARG VITE_CONSOLE_MODE
ARG VITE_APPWRITE_GROWTH_ENDPOINT=https://growth.appwrite.io/v1
ENV VITE_GA_PROJECT=$VITE_GA_PROJECT
ENV VITE_CONSOLE_MODE=$VITE_CONSOLE_MODE
ENV VITE_APPWRITE_GROWTH_ENDPOINT=$VITE_APPWRITE_GROWTH_ENDPOINT
COPY package-lock.json /usr/local/src/
COPY package.json /usr/local/src/
COPY gulpfile.js /usr/local/src/
COPY public /usr/local/src/public
RUN npm ci
RUN npm run build
FROM appwrite/base:0.2.2 as final
FROM php:8.0.18-cli-alpine3.15 as compile
ARG DEBUG=false
ENV DEBUG=$DEBUG
ENV PHP_REDIS_VERSION=5.3.7 \
PHP_MONGODB_VERSION=1.13.0 \
PHP_SWOOLE_VERSION=v4.8.10 \
PHP_IMAGICK_VERSION=3.7.0 \
PHP_YAML_VERSION=2.2.2 \
PHP_MAXMINDDB_VERSION=v1.11.0
RUN \
apk add --no-cache --virtual .deps \
make \
automake \
autoconf \
gcc \
g++ \
git \
zlib-dev \
brotli-dev \
openssl-dev \
yaml-dev \
imagemagick \
imagemagick-dev \
libmaxminddb-dev
RUN docker-php-ext-install sockets
FROM compile AS redis
RUN \
# Redis Extension
git clone --depth 1 --branch $PHP_REDIS_VERSION https://github.com/phpredis/phpredis.git && \
cd phpredis && \
phpize && \
./configure && \
make && make install
## Swoole Extension
FROM compile AS swoole
RUN \
git clone --depth 1 --branch $PHP_SWOOLE_VERSION https://github.com/swoole/swoole-src.git && \
cd swoole-src && \
phpize && \
./configure --enable-sockets --enable-http2 --enable-openssl && \
make && make install && \
cd ..
## Swoole Debugger setup
RUN if [ "$DEBUG" == "true" ]; then \
cd /tmp && \
apk add boost-dev && \
git clone --depth 1 https://github.com/swoole/yasd && \
cd yasd && \
phpize && \
./configure && \
make && make install && \
cd ..;\
fi
## Imagick Extension
FROM compile AS imagick
RUN \
git clone --depth 1 --branch $PHP_IMAGICK_VERSION https://github.com/imagick/imagick && \
cd imagick && \
phpize && \
./configure && \
make && make install
## YAML Extension
FROM compile AS yaml
RUN \
git clone --depth 1 --branch $PHP_YAML_VERSION https://github.com/php/pecl-file_formats-yaml && \
cd pecl-file_formats-yaml && \
phpize && \
./configure && \
make && make install
## Maxminddb extension
FROM compile AS maxmind
RUN \
git clone --depth 1 --branch $PHP_MAXMINDDB_VERSION https://github.com/maxmind/MaxMind-DB-Reader-php.git && \
cd MaxMind-DB-Reader-php && \
cd ext && \
phpize && \
./configure && \
make && make install
# Mongodb Extension
FROM compile as mongodb
RUN \
git clone --depth 1 --branch $PHP_MONGODB_VERSION https://github.com/mongodb/mongo-php-driver.git && \
cd mongo-php-driver && \
git submodule update --init && \
phpize && \
./configure && \
make && make install
FROM php:8.0.18-cli-alpine3.15 as final
LABEL maintainer="team@appwrite.io"
@@ -99,8 +193,8 @@ ENV _APP_SERVER=swoole \
_APP_SMTP_SECURE= \
_APP_SMTP_USERNAME= \
_APP_SMTP_PASSWORD= \
_APP_SMS_PROVIDER= \
_APP_SMS_FROM= \
_APP_PHONE_PROVIDER= \
_APP_PHONE_FROM= \
_APP_FUNCTIONS_SIZE_LIMIT=30000000 \
_APP_FUNCTIONS_TIMEOUT=900 \
_APP_FUNCTIONS_CONTAINERS=10 \
@@ -113,17 +207,47 @@ ENV _APP_SERVER=swoole \
_APP_SETUP=self-hosted \
_APP_VERSION=$VERSION \
_APP_USAGE_STATS=enabled \
_APP_USAGE_AGGREGATION_INTERVAL=30 \
# 14 Days = 1209600 s
_APP_MAINTENANCE_RETENTION_EXECUTION=1209600 \
_APP_MAINTENANCE_RETENTION_AUDIT=1209600 \
# 1 Day = 86400 s
_APP_MAINTENANCE_RETENTION_ABUSE=86400 \
_APP_MAINTENANCE_RETENTION_USAGE_HOURLY=8640000 \
_APP_MAINTENANCE_INTERVAL=86400 \
_APP_LOGGING_PROVIDER= \
_APP_LOGGING_CONFIG=
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN \
apk update \
&& apk add --no-cache --virtual .deps \
make \
automake \
autoconf \
gcc \
g++ \
curl-dev \
&& apk add --no-cache \
libstdc++ \
certbot \
brotli-dev \
yaml-dev \
imagemagick \
imagemagick-dev \
libmaxminddb-dev \
certbot \
docker-cli \
libgomp \
&& docker-php-ext-install sockets opcache pdo_mysql \
&& apk del .deps \
&& rm -rf /var/cache/apk/*
RUN \
mkdir -p $DOCKER_CONFIG/cli-plugins \
&& ARCH=$(uname -m) && if [ $ARCH == "armv7l" ]; then ARCH="armv7"; fi \
&& curl -SL https://github.com/docker/compose/releases/download/$DOCKER_COMPOSE_VERSION/docker-compose-linux-$ARCH -o $DOCKER_CONFIG/cli-plugins/docker-compose \
&& chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose
RUN \
if [ "$DEBUG" == "true" ]; then \
apk add boost boost-dev; \
@@ -132,12 +256,20 @@ RUN \
WORKDIR /usr/src/code
COPY --from=composer /usr/local/src/vendor /usr/src/code/vendor
COPY --from=node /usr/local/src/console/build /usr/src/code/console
COPY --from=node /usr/local/src/public/dist /usr/src/code/public/dist
COPY --from=swoole /usr/local/lib/php/extensions/no-debug-non-zts-20200930/swoole.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/yasd.so* /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
COPY --from=redis /usr/local/lib/php/extensions/no-debug-non-zts-20200930/redis.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
COPY --from=imagick /usr/local/lib/php/extensions/no-debug-non-zts-20200930/imagick.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
COPY --from=yaml /usr/local/lib/php/extensions/no-debug-non-zts-20200930/yaml.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
COPY --from=maxmind /usr/local/lib/php/extensions/no-debug-non-zts-20200930/maxminddb.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
COPY --from=mongodb /usr/local/lib/php/extensions/no-debug-non-zts-20200930/mongodb.so /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
# Add Source Code
COPY ./app /usr/src/code/app
COPY ./bin /usr/local/bin
COPY ./docs /usr/src/code/docs
COPY ./public/fonts /usr/src/code/public/fonts
COPY ./public/images /usr/src/code/public/images
COPY ./src /usr/src/code/src
# Set Volumes
@@ -182,7 +314,12 @@ RUN chmod +x /usr/local/bin/doctor && \
RUN mkdir -p /etc/letsencrypt/live/ && chmod -Rf 755 /etc/letsencrypt/live/
# Enable Extensions
RUN if [ "$DEBUG" == "true" ]; then printf "zend_extension=yasd \nyasd.debug_mode=remote \nyasd.init_file=/usr/src/code/dev/yasd_init.php \nyasd.remote_port=9005 \nyasd.log_level=-1" >> /usr/local/etc/php/conf.d/yasd.ini; fi
RUN echo extension=swoole.so >> /usr/local/etc/php/conf.d/swoole.ini
RUN echo extension=redis.so >> /usr/local/etc/php/conf.d/redis.ini
RUN echo extension=imagick.so >> /usr/local/etc/php/conf.d/imagick.ini
RUN echo extension=yaml.so >> /usr/local/etc/php/conf.d/yaml.ini
RUN echo extension=maxminddb.so >> /usr/local/etc/php/conf.d/maxminddb.ini
RUN if [ "$DEBUG" == "true" ]; then printf "zend_extension=yasd \nyasd.debug_mode=remote \nyasd.init_file=/usr/local/dev/yasd_init.php \nyasd.remote_port=9005 \nyasd.log_level=-1" >> /usr/local/etc/php/conf.d/yasd.ini; fi
RUN if [ "$DEBUG" == "true" ]; then echo "opcache.enable=0" >> /usr/local/etc/php/conf.d/appwrite.ini; fi
RUN echo "opcache.preload_user=www-data" >> /usr/local/etc/php/conf.d/appwrite.ini
@@ -194,4 +331,4 @@ RUN echo "opcache.jit=1235" >> /usr/local/etc/php/conf.d/appwrite.ini
EXPOSE 80
CMD [ "php", "app/http.php", "-dopcache.preload=opcache.preload=/usr/src/code/app/preload.php" ]
CMD [ "php", "app/http.php", "-dopcache.preload=opcache.preload=/usr/src/code/app/preload.php" ]
+17 -25
View File
@@ -1,6 +1,3 @@
> 准备好迎接狂风暴'云'了吗? 🌩 ☂️
> Appwrite Cloud即将到来!你能够通过https://appwrite.io/cloud了解更多的资讯, 注册即可领取试用额度哦
<br />
<p align="center">
<a href="https://appwrite.io" target="_blank"><img width="260" height="39" src="https://appwrite.io/images/appwrite.svg" alt="Appwrite Logo"></a>
@@ -11,22 +8,17 @@
<br />
</p>
<!-- [![Build Status](https://img.shields.io/travis/com/appwrite/appwrite?style=flat-square)](https://travis-ci.com/appwrite/appwrite) -->
[![We're Hiring](https://img.shields.io/static/v1?label=We're&message=Hiring&color=blue&style=flat-square)](https://appwrite.io/company/careers)
[![Hacktoberfest](https://img.shields.io/static/v1?label=hacktoberfest&message=friendly&color=191120&style=flat-square)](https://hacktoberfest.appwrite.io)
<!-- [![Hacktoberfest](https://img.shields.io/static/v1?label=hacktoberfest&message=friendly&color=90a88b&style=flat-square)](https://hacktoberfest.appwrite.io) -->
[![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord?r=Github)
[![Build Status](https://img.shields.io/github/actions/workflow/status/appwrite/appwrite/tests.yml?branch=master&label=tests&style=flat-square)](https://github.com/appwrite/appwrite/actions)
[![Docker Pulls](https://img.shields.io/docker/pulls/appwrite/appwrite?color=f02e65&style=flat-square)](https://hub.docker.com/r/appwrite/appwrite)
[![Build Status](https://img.shields.io/travis/com/appwrite/appwrite?style=flat-square)](https://travis-ci.com/appwrite/appwrite)
[![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite)
<!-- [![Docker Pulls](https://img.shields.io/docker/pulls/appwrite/appwrite?color=f02e65&style=flat-square)](https://hub.docker.com/r/appwrite/appwrite) -->
<!-- [![Translate](https://img.shields.io/badge/translate-f02e65?style=flat-square)](docs/tutorials/add-translations.md) -->
<!-- [![Swag Store](https://img.shields.io/badge/swag%20store-f02e65?style=flat-square)](https://store.appwrite.io) -->
[![翻译](https://img.shields.io/badge/translate-f02e65?style=flat-square)](docs/tutorials/add-translations.md)
[![周边商店](https://img.shields.io/badge/swag%20store-f02e65?style=flat-square)](https://store.appwrite.io)
[English](README.md) | 简体中文
[**宣布带有数据库关系的 Appwrite 1.3!了解最新消息!**](https://dev.to/appwrite/join-celebrations-appwrite-13-ships-relationships-57fc)
Appwrite是一个基于Docker的端到端开发者平台,其容器化的微服务库可应用于网页端,移动端,以及后端。Appwrite 通过视觉化界面简化了从零开始编写 API 的繁琐过程,在保证软件安全的前提下为开发者创造了一个高效的开发环境。
Appwrite是一个基于Docker的端到端开发者平台,其容器化的微服务库可应用于网页端,移动端,以及后端。Appwrite 通过视觉化界面极简了从零编写 API 的繁琐过程,在保证软件安全的前提下为开发者创造了一个高效的开发环境。
Appwrite 可以提供给开发者用户验证,外部授权,用户数据读写检索,文件储存,图像处理,云函数计算,[等多种服务](https://appwrite.io/docs).
@@ -58,7 +50,7 @@ Appwrite 可以提供给开发者用户验证,外部授权,用户数据读
Appwrite 的容器化服务器只需要一行指令就可以运行。您可以使用 docker-compose 在本地主机上运行 Appwrite,也可以在任何其他容器化工具(如 Kubernetes、Docker Swarm 或 Rancher)上运行 Appwrite。
启动 Appwrite 服务器的最简单方法是运行我们的 docker-compose 文件。在运行安装命令之前,请确保您的机器上安装了 [Docker](https://dockerdocs.cn/get-docker/index.html)
开始运行 Appwrite 服务器的最简单方法是运行我们的 docker-compose 文件。在运行安装命令之前,请确保您的机器上安装了 [Docker](https://dockerdocs.cn/get-docker/index.html)
### Unix
@@ -67,7 +59,7 @@ docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:1.3.1
appwrite/appwrite:0.15.2
```
### Windows
@@ -79,17 +71,17 @@ docker run -it --rm ^
--volume //var/run/docker.sock:/var/run/docker.sock ^
--volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
--entrypoint="install" ^
appwrite/appwrite:1.3.1
appwrite/appwrite:0.15.2
```
#### PowerShell
```powershell
docker run -it --rm `
--volume /var/run/docker.sock:/var/run/docker.sock `
--volume ${pwd}/appwrite:/usr/src/code/appwrite:rw `
--entrypoint="install" `
appwrite/appwrite:1.3.1
docker run -it --rm ,
--volume /var/run/docker.sock:/var/run/docker.sock ,
--volume ${pwd}/appwrite:/usr/src/code/appwrite:rw ,
--entrypoint="install" ,
appwrite/appwrite:0.15.2
```
运行后,可以在浏览器上访问 http://localhost 找到 Appwrite 控制台。在非 Linux 的本机主机上完成安装后,服务器可能需要几分钟才能启动。
@@ -136,7 +128,7 @@ docker run -it --rm `
#### 服务器
* ✅ &nbsp; [NodeJS](https://github.com/appwrite/sdk-for-node) (由 Appwrite 团队维护)
* ✅ &nbsp; [PHP](https://github.com/appwrite/sdk-for-php) (由 Appwrite 团队维护)
* ✅ &nbsp; [PHP](https://github.com/appwrite/sdk-for-php) (由 Appwr实验 团队维护)
* ✅ &nbsp; [Dart](https://github.com/appwrite/sdk-for-dart) - (由 Appwrite 团队维护)
* ✅ &nbsp; [Deno](https://github.com/appwrite/sdk-for-deno) - **公测** (由 Appwrite 团队维护)
* ✅ &nbsp; [Ruby](https://github.com/appwrite/sdk-for-ruby) (由 Appwrite 团队维护)
@@ -162,7 +154,7 @@ Appwrite API 界面层利用后台缓存和任务委派来提供极速的响应
## 贡献代码
为了确保正确审查,所有代码贡献 - 包括来自具有直接提交更改权限的贡献者 - 都必须提交PR请求并在合并分支之前得到核心开发人员的批准。
所有代码贡献 - 包括来自具有直接提交更改权限的贡献者 - 都必须提交PR请求并在合并分支之前得到核心开发人员的批准。这是为了确保正确审查所有代码。
我们欢迎所有人提交PR!如果您愿意提供帮助,可以在 [贡献指南](CONTRIBUTING.md) 中了解有关如何为项目做出贡献的更多信息。
@@ -172,7 +164,7 @@ Appwrite API 界面层利用后台缓存和任务委派来提供极速的响应
## 订阅我们
加入我们在世界各地不断发展的社区!请参阅我们的官方 [博客](https://medium.com/appwrite-io)。在 [Twitter](https://twitter.com/appwrite)、[Facebook 页面](https://www.facebook.com/appwrite.io)、[Facebook 群组](https://www.facebook.com/appwrite.io/groups/)、[开发者社区](https://dev.to/appwrite) 等平台订阅我们或加入我们的 [Discord 社区](https://discord.gg/GSeTUeA) 以获得更多帮助,想法和讨论。
加入我们在世界各地不断发展的社区!请参阅我们的官方 [博客](https://medium.com/appwrite-io)。在 [Twitter](https://twitter.com/appwrite)、[Facebook 页面](https://www.facebook.com/appwrite.io)、[Facebook 群组](https://www.facebook)、[开发者社区](https://dev.to/appwrite) 等平台订阅我们或加入我们的 [Discord 社区](https://discord.gg/GSeTUeA) 以获得更多帮助,想法和讨论。
## 版权说明
+54 -65
View File
@@ -11,33 +11,22 @@
<br />
</p>
<!-- [![Hacktoberfest](https://img.shields.io/static/v1?label=hacktoberfest&message=friendly&color=90a88b&style=flat-square)](https://hacktoberfest.appwrite.io) -->
<!-- [![Build Status](https://img.shields.io/travis/com/appwrite/appwrite?style=flat-square)](https://travis-ci.com/appwrite/appwrite) -->
[![We're Hiring](https://img.shields.io/static/v1?label=We're&message=Hiring&color=blue&style=flat-square)](https://appwrite.io/company/careers)
[![Hacktoberfest](https://img.shields.io/static/v1?label=hacktoberfest&message=ready&color=191120&style=flat-square)](https://hacktoberfest.appwrite.io)
[![Discord](https://img.shields.io/discord/564160730845151244?label=discord&style=flat-square)](https://appwrite.io/discord?r=Github)
[![Build Status](https://img.shields.io/github/actions/workflow/status/appwrite/appwrite/tests.yml?branch=master&label=tests&style=flat-square)](https://github.com/appwrite/appwrite/actions)
[![Docker Pulls](https://img.shields.io/docker/pulls/appwrite/appwrite?color=f02e65&style=flat-square)](https://hub.docker.com/r/appwrite/appwrite)
[![Build Status](https://img.shields.io/github/workflow/status/appwrite/appwrite/Tests?label=tests&style=flat-square)](https://github.com/appwrite/appwrite/actions)
[![Twitter Account](https://img.shields.io/twitter/follow/appwrite?color=00acee&label=twitter&style=flat-square)](https://twitter.com/appwrite)
<!-- [![Docker Pulls](https://img.shields.io/docker/pulls/appwrite/appwrite?color=f02e65&style=flat-square)](https://hub.docker.com/r/appwrite/appwrite) -->
<!-- [![Translate](https://img.shields.io/badge/translate-f02e65?style=flat-square)](docs/tutorials/add-translations.md) -->
<!-- [![Swag Store](https://img.shields.io/badge/swag%20store-f02e65?style=flat-square)](https://store.appwrite.io) -->
[![Translate](https://img.shields.io/badge/translate-f02e65?style=flat-square)](docs/tutorials/add-translations.md)
[![Swag Store](https://img.shields.io/badge/swag%20store-f02e65?style=flat-square)](https://store.appwrite.io)
English | [简体中文](README-CN.md)
[**Announcing Appwrite 1.3 with Database Relationships! Learn what's new!**](https://dev.to/appwrite/join-celebrations-appwrite-13-ships-relationships-57fc)
[**Appwrite 0.15 has been released! Learn what's new!**](https://dev.to/appwrite/announcing-appwrite-015-with-phone-authentication-more-5cjj)
Appwrite is an end-to-end backend server for Web, Mobile, Native, or Backend apps packaged as a set of Docker<nobr> microservices. Appwrite abstracts the complexity and repetitiveness required to build a modern backend API from scratch and allows you to build secure apps faster.
Using Appwrite, you can easily integrate your app with user authentication and multiple sign-in methods, a database for storing and querying users and team data, storage and file management, image manipulation, Cloud Functions, and [more services](https://appwrite.io/docs).
<p align="center">
<br />
<a href="https://www.producthunt.com/posts/appwrite-2?utm_source=badge-top-post-badge&utm_medium=badge&utm_souce=badge-appwrite-2" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/top-post-badge.svg?post_id=360315&theme=light&period=daily" alt="Appwrite - 100&#0037;&#0032;open&#0032;source&#0032;alternative&#0032;for&#0032;Firebase | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a>
<br />
<br />
</p>
Using Appwrite, you can easily integrate your app with user authentication & multiple sign-in methods, a database for storing and querying users and team data, storage and file management, image manipulation, Cloud Functions, and [more services](https://appwrite.io/docs).
![Appwrite](public/images/github.png)
@@ -65,7 +54,7 @@ Table of Contents:
## Installation
Appwrite is designed to run in a containerized environment. Running your server is as easy as running one command from your terminal. You can either run Appwrite on your localhost using docker-compose or on any other container orchestration tool, such as Kubernetes, Docker Swarm, or Rancher.
Appwrite backend server is designed to run in a container environment. Running your server is as easy as running one command from your terminal. You can either run Appwrite on your localhost using docker-compose or on any other container orchestration tool like Kubernetes, Docker Swarm, or Rancher.
The easiest way to start running your Appwrite server is by running our docker-compose file. Before running the installation command, make sure you have [Docker](https://www.docker.com/products/docker-desktop) installed on your machine:
@@ -76,7 +65,7 @@ docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:1.3.1
appwrite/appwrite:0.15.2
```
### Windows
@@ -88,20 +77,21 @@ docker run -it --rm ^
--volume //var/run/docker.sock:/var/run/docker.sock ^
--volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
--entrypoint="install" ^
appwrite/appwrite:1.3.1
appwrite/appwrite:0.15.2
```
#### PowerShell
```powershell
docker run -it --rm `
--volume /var/run/docker.sock:/var/run/docker.sock `
--volume ${pwd}/appwrite:/usr/src/code/appwrite:rw `
--entrypoint="install" `
appwrite/appwrite:1.3.1
docker run -it --rm ,
--volume /var/run/docker.sock:/var/run/docker.sock ,
--volume ${pwd}/appwrite:/usr/src/code/appwrite:rw ,
--entrypoint="install" ,
appwrite/appwrite:0.15.2
```
Once the Docker installation is complete, go to http://localhost to access the Appwrite console from your browser. Please note that on non-Linux native hosts, the server might take a few minutes to start after completing the installation.
Once the Docker installation completes, go to http://localhost to access the Appwrite console from your browser. Please note that on non-Linux native hosts, the server might take a few minutes to start after installation completes.
For advanced production and custom installation, check out our Docker [environment variables](https://appwrite.io/docs/environment-variables) docs. You can also use our public [docker-compose.yml](https://appwrite.io/install/compose) and [.env](https://appwrite.io/install/env) files to manually set up an environment.
@@ -109,9 +99,10 @@ For advanced production and custom installation, check out our Docker [environme
If you are upgrading your Appwrite server from an older version, you should use the Appwrite migration tool once your setup is completed. For more information regarding this, check out the [Installation Docs](https://appwrite.io/docs/installation).
## One-Click Setups
In addition to running Appwrite locally, you can also launch Appwrite using a pre-configured setup. This allows you to get up and running quickly with Appwrite without installing Docker on your local machine.
In addition to running Appwrite locally, you can also launch Appwrite using a pre-configured setup. This allows you to get up and running with Appwrite quickly without installing Docker on your local machine.
Choose from one of the providers below:
@@ -136,68 +127,66 @@ Choose from one of the providers below:
Getting started with Appwrite is as easy as creating a new project, choosing your platform, and integrating its SDK into your code. You can easily get started with your platform of choice by reading one of our Getting Started tutorials.
- [Getting Started for Web](https://appwrite.io/docs/getting-started-for-web)
- [Getting Started for Flutter](https://appwrite.io/docs/getting-started-for-flutter)
- [Getting Started for Apple](https://appwrite.io/docs/getting-started-for-apple)
- [Getting Started for Android](https://appwrite.io/docs/getting-started-for-android)
- [Getting Started for Server](https://appwrite.io/docs/getting-started-for-server)
- [Getting Started for CLI](https://appwrite.io/docs/command-line)
* [Getting Started for Web](https://appwrite.io/docs/getting-started-for-web)
* [Getting Started for Flutter](https://appwrite.io/docs/getting-started-for-flutter)
* [Getting Started for Apple](https://appwrite.io/docs/getting-started-for-apple)
* [Getting Started for Android](https://appwrite.io/docs/getting-started-for-android)
* [Getting Started for Server](https://appwrite.io/docs/getting-started-for-server)
* [Getting Started for CLI](https://appwrite.io/docs/command-line)
### Services
- [**Account**](https://appwrite.io/docs/client/account) - Manage current user authentication and account. Track and manage the user sessions, devices, sign-in methods, and security logs.
- [**Users**](https://appwrite.io/docs/server/users) - Manage and list all project users when building backend integrations with Server SDKs.
- [**Teams**](https://appwrite.io/docs/client/teams) - Manage and group users in teams. Manage memberships, invites, and user roles within a team.
- [**Databases**](https://appwrite.io/docs/client/databases) - Manage databases, collections, and documents. Read, create, update, and delete documents and filter lists of document collections using advanced filters.
- [**Storage**](https://appwrite.io/docs/client/storage) - Manage storage files. Read, create, delete, and preview files. Manipulate the preview of your files to perfectly fit your app. All files are scanned by ClamAV and stored in a secure and encrypted way.
- [**Functions**](https://appwrite.io/docs/server/functions) - Customize your Appwrite server by executing your custom code in a secure, isolated environment. You can trigger your code on any Appwrite system event either manually or using a CRON schedule.
- [**Realtime**](https://appwrite.io/docs/realtime) - Listen to real-time events for any of your Appwrite services including users, storage, functions, databases, and more.
- [**Locale**](https://appwrite.io/docs/client/locale) - Track your user's location and manage your app locale-based data.
- [**Avatars**](https://appwrite.io/docs/client/avatars) - Manage your users' avatars, countries' flags, browser icons, and credit card symbols. Generate QR codes from links or plaintext strings.
* [**Account**](https://appwrite.io/docs/client/account) - Manage current user authentication and account. Track and manage the user sessions, devices, sign-in methods, and security logs.
* [**Users**](https://appwrite.io/docs/server/users) - Manage and list all project users when in admin mode.
* [**Teams**](https://appwrite.io/docs/client/teams) - Manage and group users in teams. Manage memberships, invites, and user roles within a team.
* [**Databases**](https://appwrite.io/docs/client/databases) - Manage databases, collections and documents. Read, create, update, and delete documents and filter lists of document collections using advanced filters.
* [**Storage**](https://appwrite.io/docs/client/storage) - Manage storage files. Read, create, delete, and preview files. Manipulate the preview of your files to fit your app perfectly. All files are scanned by ClamAV and stored in a secure and encrypted way.
* [**Functions**](https://appwrite.io/docs/server/functions) - Customize your Appwrite server by executing your custom code in a secure, isolated environment. You can trigger your code on any Appwrite system event, manually or using a CRON schedule.
* [**Realtime**](https://appwrite.io/docs/realtime) - Listen to real-time events for any of your Appwrite services including users, storage, functions, databases and more.
* [**Locale**](https://appwrite.io/docs/client/locale) - Track your user's location, and manage your app locale-based data.
* [**Avatars**](https://appwrite.io/docs/client/avatars) - Manage your users' avatars, countries' flags, browser icons, credit card symbols, and generate QR codes.
For the complete API documentation, visit [https://appwrite.io/docs](https://appwrite.io/docs). For more tutorials, news and announcements check out our [blog](https://medium.com/appwrite-io) and [Discord Server](https://discord.gg/GSeTUeA).
### SDKs
Below is a list of currently supported platforms and languages. If you would like to help us add support to your platform of choice, you can go over to our [SDK Generator](https://github.com/appwrite/sdk-generator) project and view our [contribution guide](https://github.com/appwrite/sdk-generator/blob/master/CONTRIBUTING.md).
Below is a list of currently supported platforms and languages. If you wish to help us add support to your platform of choice, you can go over to our [SDK Generator](https://github.com/appwrite/sdk-generator) project and view our [contribution guide](https://github.com/appwrite/sdk-generator/blob/master/CONTRIBUTING.md).
#### Client
- ✅ &nbsp; [Web](https://github.com/appwrite/sdk-for-web) (Maintained by the Appwrite Team)
- ✅ &nbsp; [Flutter](https://github.com/appwrite/sdk-for-flutter) (Maintained by the Appwrite Team)
- ✅ &nbsp; [Apple](https://github.com/appwrite/sdk-for-apple) - **Beta** (Maintained by the Appwrite Team)
- ✅ &nbsp; [Android](https://github.com/appwrite/sdk-for-android) (Maintained by the Appwrite Team)
* ✅ &nbsp; [Web](https://github.com/appwrite/sdk-for-web) (Maintained by the Appwrite Team)
* &nbsp; [Flutter](https://github.com/appwrite/sdk-for-flutter) (Maintained by the Appwrite Team)
* &nbsp; [Apple](https://github.com/appwrite/sdk-for-apple) - **Beta** (Maintained by the Appwrite Team)
* &nbsp; [Android](https://github.com/appwrite/sdk-for-android) (Maintained by the Appwrite Team)
#### Server
- ✅ &nbsp; [NodeJS](https://github.com/appwrite/sdk-for-node) (Maintained by the Appwrite Team)
- ✅ &nbsp; [PHP](https://github.com/appwrite/sdk-for-php) (Maintained by the Appwrite Team)
- ✅ &nbsp; [Dart](https://github.com/appwrite/sdk-for-dart) - (Maintained by the Appwrite Team)
- ✅ &nbsp; [Deno](https://github.com/appwrite/sdk-for-deno) - **Beta** (Maintained by the Appwrite Team)
- ✅ &nbsp; [Ruby](https://github.com/appwrite/sdk-for-ruby) (Maintained by the Appwrite Team)
- ✅ &nbsp; [Python](https://github.com/appwrite/sdk-for-python) (Maintained by the Appwrite Team)
- ✅ &nbsp; [Kotlin](https://github.com/appwrite/sdk-for-kotlin) - **Beta** (Maintained by the Appwrite Team)
- ✅ &nbsp; [Apple](https://github.com/appwrite/sdk-for-apple) - **Beta** (Maintained by the Appwrite Team)
- ✅ &nbsp; [.NET](https://github.com/appwrite/sdk-for-dotnet) - **Experimental** (Maintained by the Appwrite Team)
* ✅ &nbsp; [NodeJS](https://github.com/appwrite/sdk-for-node) (Maintained by the Appwrite Team)
* &nbsp; [PHP](https://github.com/appwrite/sdk-for-php) (Maintained by the Appwrite Team)
* &nbsp; [Dart](https://github.com/appwrite/sdk-for-dart) - (Maintained by the Appwrite Team)
* &nbsp; [Deno](https://github.com/appwrite/sdk-for-deno) - **Beta** (Maintained by the Appwrite Team)
* &nbsp; [Ruby](https://github.com/appwrite/sdk-for-ruby) (Maintained by the Appwrite Team)
* &nbsp; [Python](https://github.com/appwrite/sdk-for-python) (Maintained by the Appwrite Team)
* &nbsp; [Kotlin](https://github.com/appwrite/sdk-for-kotlin) - **Beta** (Maintained by the Appwrite Team)
* &nbsp; [Apple](https://github.com/appwrite/sdk-for-apple) - **Beta** (Maintained by the Appwrite Team)
* &nbsp; [.NET](https://github.com/appwrite/sdk-for-dotnet) - **Experimental** (Maintained by the Appwrite Team)
#### Community
- ✅ &nbsp; [Appcelerator Titanium](https://github.com/m1ga/ti.appwrite) (Maintained by [Michael Gangolf](https://github.com/m1ga/))
- ✅ &nbsp; [Godot Engine](https://github.com/GodotNuts/appwrite-sdk) (Maintained by [fenix-hub @GodotNuts](https://github.com/fenix-hub))
* ✅ &nbsp; [Appcelerator Titanium](https://github.com/m1ga/ti.appwrite) (Maintained by [Michael Gangolf](https://github.com/m1ga/))
* &nbsp; [Godot Engine](https://github.com/GodotNuts/appwrite-sdk) (Maintained by [fenix-hub @GodotNuts](https://github.com/fenix-hub))
Looking for more SDKs? - Help us by contributing a pull request to our [SDK Generator](https://github.com/appwrite/sdk-generator)!
## Architecture
![Appwrite Architecture](docs/specs/overview.drawio.svg)
Appwrite uses a microservices architecture that was designed for easy scaling and delegation of responsibilities. In addition, Appwrite supports multiple APIs, such as REST, WebSocket, and GraphQL to allow you to interact with your resources by leveraging your existing knowledge and protocols of choice.
Appwrite uses a microservices architecture that was designed for easy scaling and delegation of responsibilities. In addition, Appwrite supports multiple APIs (REST, WebSocket, and GraphQL-soon) to allow you to interact with your resources leveraging your existing knowledge and protocols of choice.
The Appwrite API layer was designed to be extremely fast by leveraging in-memory caching and delegating any heavy-lifting tasks to the Appwrite background workers. The background workers also allow you to precisely control your compute capacity and costs using a message queue to handle the load. You can learn more about our architecture in the [contribution guide](CONTRIBUTING.md#architecture-1).
## Contributing
All code contributions, including those of people having commit access, must go through a pull request and be approved by a core developer before being merged. This is to ensure a proper review of all the code.
All code contributions - including those of people having commit access - must go through a pull request and be approved by a core developer before being merged. This is to ensure a proper review of all the code.
We truly ❤️ pull requests! If you wish to help, you can learn more about how you can contribute to this project in the [contribution guide](CONTRIBUTING.md).
@@ -207,7 +196,7 @@ For security issues, kindly email us at [security@appwrite.io](mailto:security@a
## Follow Us
Join our growing community around the world! Check out our official [Blog](https://medium.com/appwrite-io). Follow us on [Twitter](https://twitter.com/appwrite), [Facebook Page](https://www.facebook.com/appwrite.io), [Facebook Group](https://www.facebook.com/groups/appwrite.developers/), [Dev Community](https://dev.to/appwrite) or join our live [Discord server](https://discord.gg/GSeTUeA) for more help, ideas, and discussions.
Join our growing community around the world! See our official [Blog](https://medium.com/appwrite-io). Follow us on [Twitter](https://twitter.com/appwrite), [Facebook Page](https://www.facebook.com/appwrite.io), [Facebook Group](https://www.facebook.com/groups/appwrite.developers/) , [Dev Community](https://dev.to/appwrite) or join our live [Discord server](https://discord.gg/GSeTUeA) for more help, ideas, and discussions.
## License
+5 -7
View File
@@ -2,13 +2,11 @@
## Supported Versions
| Version | Supported |
| --------- | ------------------ |
| <= 0.15.x | :x: |
| 1.0.x | :white_check_mark: |
| 1.1.x | :white_check_mark: |
| 1.2.x | :white_check_mark: |
| 1.3.x | :white_check_mark: |
| Version | Supported |
| ------- | ------------------ |
| <= 0.10 | :x: |
| 0.11.x | :white_check_mark: |
| 0.12.x | :white_check_mark: |
## Reporting a Vulnerability
Binary file not shown.
File diff suppressed because it is too large Load Diff
+2757 -3363
View File
File diff suppressed because it is too large Load Diff
+20 -87
View File
@@ -50,7 +50,7 @@ return [
],
Exception::GENERAL_PHONE_DISABLED => [
'name' => Exception::GENERAL_PHONE_DISABLED,
'description' => 'Phone provider is not configured. Please check the _APP_SMS_PROVIDER environment variable of your Appwrite server.',
'description' => 'Phone provider is not configured. Please check the _APP_PHONE_PROVIDER environment variable of your Appwrite server.',
'code' => 503,
],
Exception::GENERAL_ARGUMENT_INVALID => [
@@ -70,7 +70,7 @@ return [
],
Exception::GENERAL_ROUTE_NOT_FOUND => [
'name' => Exception::GENERAL_ROUTE_NOT_FOUND,
'description' => 'The requested route was not found. Please refer to the API docs and try again.',
'description' => 'The requested route was not found. Please refer to the docs and try again.',
'code' => 404,
],
Exception::GENERAL_CURSOR_NOT_FOUND => [
@@ -102,7 +102,7 @@ return [
],
Exception::USER_ALREADY_EXISTS => [
'name' => Exception::USER_ALREADY_EXISTS,
'description' => 'A user with the same email already exists in your project.',
'description' => 'A user with the same email ID already exists in your project.',
'code' => 409,
],
Exception::USER_BLOCKED => [
@@ -122,12 +122,12 @@ return [
],
Exception::USER_EMAIL_NOT_WHITELISTED => [
'name' => Exception::USER_EMAIL_NOT_WHITELISTED,
'description' => 'Console registration is restricted to specific emails. Contact your administrator for more information.',
'description' => 'The user\'s email is not part of the whitelist. Please check the _APP_CONSOLE_WHITELIST_EMAILS environment variable of your Appwrite server.',
'code' => 401,
],
Exception::USER_IP_NOT_WHITELISTED => [
'name' => Exception::USER_IP_NOT_WHITELISTED,
'description' => 'Console registration is restricted to specific IPs. Contact your administrator for more information.',
'description' => 'The user\'s IP address is not part of the whitelist. Please check the _APP_CONSOLE_WHITELIST_IPS environment variable of your Appwrite server.',
'code' => 401,
],
Exception::USER_INVALID_CREDENTIALS => [
@@ -152,7 +152,7 @@ return [
],
Exception::USER_EMAIL_ALREADY_EXISTS => [
'name' => Exception::USER_EMAIL_ALREADY_EXISTS,
'description' => 'A user with the same email already exists in the current project.',
'description' => 'Another user with the same email already exists in the current project.',
'code' => 409,
],
Exception::USER_PASSWORD_MISMATCH => [
@@ -185,11 +185,6 @@ return [
'description' => 'The current user does not have a phone number associated with their account.',
'code' => 400,
],
Exception::USER_MISSING_ID => [
'name' => Exception::USER_MISSING_ID,
'description' => 'Missing ID from OAuth2 provider.',
'code' => 400,
],
/** Teams */
Exception::TEAM_NOT_FOUND => [
@@ -199,7 +194,7 @@ return [
],
Exception::TEAM_INVITE_ALREADY_EXISTS => [
'name' => Exception::TEAM_INVITE_ALREADY_EXISTS,
'description' => 'User has already been invited or is already a member of this team',
'description' => 'The current user has already received an invitation to join the team.',
'code' => 409,
],
Exception::TEAM_INVITE_NOT_FOUND => [
@@ -223,17 +218,13 @@ return [
'code' => 401,
],
/** Membership */
Exception::MEMBERSHIP_NOT_FOUND => [
'name' => Exception::MEMBERSHIP_NOT_FOUND,
'description' => 'Membership with the requested ID could not be found.',
'code' => 404,
],
Exception::MEMBERSHIP_ALREADY_CONFIRMED => [
'name' => Exception::MEMBERSHIP_ALREADY_CONFIRMED,
'description' => 'Membership already confirmed',
'code' => 409,
],
/** Avatars */
Exception::AVATAR_SET_NOT_FOUND => [
@@ -280,7 +271,7 @@ return [
],
Exception::STORAGE_FILE_TYPE_UNSUPPORTED => [
'name' => Exception::STORAGE_FILE_TYPE_UNSUPPORTED,
'description' => 'The given file extension is not supported.',
'description' => 'The file type is not supported.',
'code' => 400,
],
Exception::STORAGE_INVALID_FILE_SIZE => [
@@ -334,7 +325,7 @@ return [
],
Exception::BUILD_NOT_READY => [
'name' => Exception::BUILD_NOT_READY,
'description' => 'Build with the requested ID is building and not ready for execution.',
'description' => 'Build with the requested ID is builing and not ready for execution.',
'code' => 400,
],
Exception::BUILD_IN_PROGRESS => [
@@ -357,19 +348,6 @@ return [
'code' => 404,
],
/** Databases */
Exception::DATABASE_NOT_FOUND => [
'name' => Exception::DATABASE_NOT_FOUND,
'description' => 'Database not found',
'code' => 404
],
Exception::DATABASE_ALREADY_EXISTS => [
'name' => Exception::DATABASE_ALREADY_EXISTS,
'description' => 'Database already exists',
'code' => 409
],
/** Collections */
Exception::COLLECTION_NOT_FOUND => [
'name' => Exception::COLLECTION_NOT_FOUND,
@@ -408,16 +386,6 @@ return [
'description' => 'Document with the requested ID already exists.',
'code' => 409,
],
Exception::DOCUMENT_UPDATE_CONFLICT => [
'name' => Exception::DOCUMENT_UPDATE_CONFLICT,
'description' => 'Remote document is newer than local.',
'code' => 409,
],
Exception::DOCUMENT_DELETE_RESTRICTED => [
'name' => Exception::DOCUMENT_DELETE_RESTRICTED,
'description' => 'Document cannot be deleted because it is referenced by another document.',
'code' => 403,
],
/** Attributes */
Exception::ATTRIBUTE_NOT_FOUND => [
@@ -427,12 +395,12 @@ return [
],
Exception::ATTRIBUTE_UNKNOWN => [
'name' => Exception::ATTRIBUTE_UNKNOWN,
'description' => 'The attribute required for the index could not be found. Please confirm all your attributes are in the available state.',
'description' => 'The attribute required for the index could not be found. Please confirm all your attributes are in the <span class="tag">available</span> state.',
'code' => 400,
],
Exception::ATTRIBUTE_NOT_AVAILABLE => [
'name' => Exception::ATTRIBUTE_NOT_AVAILABLE,
'description' => 'The requested attribute is not yet available. Please try again later.',
'description' => 'The requested attribute is not yet <span class="tag">available</span>. Please try again later.',
'code' => 400,
],
Exception::ATTRIBUTE_FORMAT_UNSUPPORTED => [
@@ -442,7 +410,7 @@ return [
],
Exception::ATTRIBUTE_DEFAULT_UNSUPPORTED => [
'name' => Exception::ATTRIBUTE_DEFAULT_UNSUPPORTED,
'description' => 'Default values cannot be set for array or required attributes.',
'description' => 'Default values cannot be set for <span class="tag">array</span> and <span class="tag">required</span> attributes.',
'code' => 400,
],
Exception::ATTRIBUTE_ALREADY_EXISTS => [
@@ -460,11 +428,6 @@ return [
'description' => 'The attribute value is invalid. Please check the type, range and value of the attribute.',
'code' => 400,
],
Exception::ATTRIBUTE_TYPE_INVALID => [
'name' => Exception::ATTRIBUTE_TYPE_INVALID,
'description' => 'The attribute type is invalid.',
'code' => 400,
],
/** Indexes */
Exception::INDEX_NOT_FOUND => [
@@ -501,29 +464,24 @@ return [
],
Exception::PROJECT_PROVIDER_UNSUPPORTED => [
'name' => Exception::PROJECT_PROVIDER_UNSUPPORTED,
'description' => 'The chosen OAuth provider is unsupported. Please check the <a href="/docs/client/account?sdk=web-default#accountCreateOAuth2Session">Create OAuth2 Session docs</a> for the complete list of supported OAuth providers.',
'description' => 'The chosen OAuth provider is unsupported. Please check <a href="/docs/client/account?sdk=web-default#accountCreateOAuth2Session"> the docs</a> for the complete list of supported OAuth providers.',
'code' => 501,
],
Exception::PROJECT_INVALID_SUCCESS_URL => [
'name' => Exception::PROJECT_INVALID_SUCCESS_URL,
'description' => 'Invalid redirect URL for OAuth success.',
'description' => 'Invalid URL received for OAuth success redirect.',
'code' => 400,
],
Exception::PROJECT_INVALID_FAILURE_URL => [
'name' => Exception::PROJECT_INVALID_FAILURE_URL,
'description' => 'Invalid redirect URL for OAuth failure.',
'description' => 'Invalid URL received for OAuth failure redirect.',
'code' => 400,
],
Exception::PROJECT_RESERVED_PROJECT => [
'name' => Exception::PROJECT_RESERVED_PROJECT,
'description' => 'The project ID is reserved. Please choose another project ID.',
Exception::PROJECT_MISSING_USER_ID => [
'name' => Exception::PROJECT_MISSING_USER_ID,
'description' => 'Failed to obtain user ID from the OAuth provider.',
'code' => 400,
],
Exception::PROJECT_KEY_EXPIRED => [
'name' => Exception::PROJECT_KEY_EXPIRED,
'description' => 'The project key has expired. Please generate a new key using the Appwrite console.',
'code' => 401,
],
Exception::WEBHOOK_NOT_FOUND => [
'name' => Exception::WEBHOOK_NOT_FOUND,
'description' => 'Webhook with the requested ID could not be found.',
@@ -549,34 +507,9 @@ return [
'description' => 'A Domain with the requested ID already exists.',
'code' => 409,
],
Exception::VARIABLE_NOT_FOUND => [
'name' => Exception::VARIABLE_NOT_FOUND,
'description' => 'Variable with the requested ID could not be found.',
'code' => 404,
],
Exception::VARIABLE_ALREADY_EXISTS => [
'name' => Exception::VARIABLE_ALREADY_EXISTS,
'description' => 'Variable with the same ID already exists in your project.',
'code' => 409,
],
Exception::DOMAIN_VERIFICATION_FAILED => [
'name' => Exception::DOMAIN_VERIFICATION_FAILED,
'description' => 'Domain verification for the requested domain has failed.',
'code' => 401,
],
Exception::DOMAIN_TARGET_INVALID => [
'name' => Exception::DOMAIN_TARGET_INVALID,
'description' => 'Your Appwrite instance is not publicly accessible. Please check the _APP_DOMAIN_TARGET environment variable of your Appwrite server.',
'code' => 501,
],
Exception::GRAPHQL_NO_QUERY => [
'name' => Exception::GRAPHQL_NO_QUERY,
'description' => 'Param "query" is not optional.',
'code' => 400,
],
Exception::GRAPHQL_TOO_MANY_QUERIES => [
'name' => Exception::GRAPHQL_TOO_MANY_QUERIES,
'description' => 'Too many queries.',
'code' => 400,
],
]
];
+4 -7
View File
@@ -1,7 +1,7 @@
<?php
/**
* List of publicly accessible system events
* List of publicly accessiable system events
*/
use Appwrite\Utopia\Response;
@@ -183,16 +183,13 @@ return [
],
],
'create' => [
'$description' => 'This event triggers when a team is created.'
'$description' => 'This event triggers when a bucket is created.'
],
'delete' => [
'$description' => 'This event triggers when a team is deleted.',
'$description' => 'This event triggers when a bucket is deleted.',
],
'update' => [
'$description' => 'This event triggers when a team is updated.',
'prefs' => [
'$description' => 'This event triggers when a team\'s preferences are updated.',
],
'$description' => 'This event triggers when a bucket is updated.',
]
],
'functions' => [
+2 -2
View File
@@ -17,7 +17,7 @@
"emails.magicSession.signature": "L'équipe {{project}}",
"emails.recovery.subject": "Réinitialisation du mot de passe",
"emails.recovery.hello": "Bonjour {{name}}",
"emails.recovery.body": "Suivez ce lien pour réinitialiser votre mot de passe pour {{project}}.",
"emails.recovery.body": "Suivez ce lien pour réinitialiser votre mot de passe pour {{projet}}.",
"emails.recovery.footer": "Si vous n'avez pas demandé à réinitialiser votre mot de passe, vous pouvez ignorer ce message.",
"emails.recovery.thanks": "Merci",
"emails.recovery.signature": "L'équipe {{project}}",
@@ -29,7 +29,7 @@
"emails.invitation.signature": "L'équipe {{project}}",
"emails.certificate.subject": "Échec du certificat pour %s",
"emails.certificate.hello": "Bonjour",
"emails.certificate.body": "Le certificate pour votre domaine '{{domain}}' n'a pas pu être généré. Ceci est la tentative {{attempt}} et l'échec a été causé par : {{error}}",
"emails.certificate.body": "Le certificate pour votre domaine '{{domain}}' n'a pas pu être généré. Ceci est la tentative {{tentative}} et l'échec a été causé par : {{erreur}}",
"emails.certificate.footer": "Votre certificat précédent sera valide pendant 30 jours à compter de la première défaillance. Nous vous recommandons fortement d'enquêter sur ce cas, sinon votre domaine se retrouvera sans communication SSL valide.",
"emails.certificate.thanks": "Merci",
"emails.certificate.signature": "L'équipe {{project}}",
+7 -7
View File
@@ -6,25 +6,25 @@
"emails.verification.subject": "अकाउंट वेरिफिकेशन ",
"emails.verification.hello": "नमस्ते {{name}}",
"emails.verification.body": "इस लिंक के माध्यम से अपने ईमेल को सत्यापित कीजिये।",
"emails.verification.footer": "यदि आप इस पते को सत्यापित नहीं करना चाहते है, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.verification.footer": "यदि आपने इस पते को सत्यापित नहीं करना चाहते है, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.verification.thanks": "धन्यवाद",
"emails.verification.signature": "{{project}} टीम",
"emails.magicSession.subject": "लॉग इन",
"emails.magicSession.hello": "नमस्ते,",
"emails.magicSession.body": "इस लिंक के माध्यम से लॉग-इन करें।",
"emails.magicSession.footer": "यदि आप इस ईमेल द्वारा लॉगिन नहीं करना चाहते है, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.magicSession.footer": "यदि आप इस ईमेल द्वारा लॉगिन नहीं करना चाहते है, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.magicSession.thanks": "धन्यवाद",
"emails.magicSession.signature": "{{project}} टीम",
"emails.recovery.subject": "पासवर्ड रीसेट",
"emails.recovery.hello": "नमस्ते {{name}}",
"emails.recovery.body": "इस लिंक के माध्यम से अपना {{project}} पासवर्ड रीसेट करें।",
"emails.recovery.footer": "यदि आप अपना पासवर्ड रसेट नहीं करना चाहते है, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.recovery.footer": "यदि आप अपना पासवर्ड रिसेट नहीं करना चाहते है, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.recovery.thanks": "धन्यवाद",
"emails.recovery.signature": "{{project}} टीम",
"emails.invitation.subject": "%s टीम का यहाँ %s पर आमंत्रण",
"emails.invitation.hello": "नमस्ते",
"emails.invitation.body": "यह मेल आपको इसलिए भेजा गया है क्योंकि {{owner}} आपको {{team}} टीम का सदस्य बनाना चाहते है, जो {{project}} से जुड़ा हुआ है।",
"emails.invitation.footer": "यदि आप इसमे रूचि नहीं रखते, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.invitation.body": "यह मेल आपको इसलिए भेजा गया था क्योंकि {{owner}} आपको {{team}} टीम का सदस्य बनाना चाहते थे, जो {{project}} से जुड़ा हुआ है।",
"emails.invitation.footer": "यदि आप इसमे रूचि नहीं रखते, तो आप इस संदेश को नज़रअंदाज़ कर सकते हैं।",
"emails.invitation.thanks": "धन्यवाद",
"emails.invitation.signature": "{{project}} टीम",
"locale.country.unknown": "अज्ञात",
@@ -35,7 +35,7 @@
"countries.ae": "संयुक्त अरब अमीरात",
"countries.ar": "अर्जेंटीना",
"countries.am": "आर्मीनिया",
"countries.ag": "ंटीगुआ और बारबूडा",
"countries.ag": "ंटीगुआ और बारबूडा",
"countries.au": "ऑस्ट्रेलिया",
"countries.at": "ऑस्ट्रिया",
"countries.az": "अज़रबैजान",
@@ -46,7 +46,7 @@
"countries.bd": "बांग्लादेश",
"countries.bg": "बुल्गारिया",
"countries.bh": "बहरीन",
"countries.bs": "द बाहामास",
"countries.bs": "हामास",
"countries.ba": "बॉस्निया और हर्ज़ेगोविना",
"countries.by": "बेलारूस",
"countries.bz": "बेलीज़",
+96 -102
View File
@@ -5,63 +5,57 @@
"emails.sender": "%s 小組",
"emails.verification.subject": "帳戶驗證",
"emails.verification.hello": "嗨 {{name}}",
"emails.verification.body": "按照此連結驗證您的電子郵件地址。",
"emails.verification.body": "按照此鏈接驗證您的電子郵件地址。",
"emails.verification.footer": "如果您沒有要求驗證此地址,則可以忽略此消息。",
"emails.verification.thanks": "謝謝",
"emails.verification.signature": "{{project}} 團隊",
"emails.magicSession.subject": "登",
"emails.magicSession.hello": "嗨",
"emails.magicSession.body": "點此連結登入。",
"emails.magicSession.footer": "如果您沒有要求使用此電子郵件登,則可以忽略此消息。",
"emails.magicSession.subject": "登",
"emails.magicSession.hello": "嗨",
"emails.magicSession.body": "點此鏈接登錄。",
"emails.magicSession.footer": "如果您沒有要求使用此電子郵件登,則可以忽略此消息。",
"emails.magicSession.thanks": "謝謝",
"emails.magicSession.signature": "{{project}} 團隊",
"emails.recovery.subject": "重設密碼",
"emails.recovery.hello": "好 {{name}}",
"emails.recovery.body": "按照此連結重置您的 {{project}} 密碼",
"emails.recovery.hello": "好 {{name}}",
"emails.recovery.body": "按照此鏈接重置您的 {{project}} 密碼.",
"emails.recovery.footer": "如果您沒有要求重置密碼,則可以忽略此消息。",
"emails.recovery.thanks": "謝謝",
"emails.recovery.signature": "{{project}} 團隊",
"emails.invitation.subject": "邀請 %s 團隊在 %s",
"emails.invitation.hello": "好",
"emails.invitation.body": "發送這封郵件給您是因為 {{owner}} 想邀請您成為 {{team}} 團隊在 {{project}}",
"emails.invitation.hello": "好",
"emails.invitation.body": "這封郵件發送給您是因為 {{owner}} 想邀請您成為 {{team}} 團隊在 {{project}}.",
"emails.invitation.footer": "如果您不感興趣,可以忽略此消息。",
"emails.invitation.thanks": "謝謝",
"emails.invitation.signature": "{{project}} 團隊",
"emails.certificate.subject": "%s 的憑證更新失敗",
"emails.certificate.hello": "您好",
"emails.certificate.body": "無法產生您的域名 '{{domain}}' 的憑證。這是第 {{attempt}} 次嘗試,失敗原因是:{{error}}",
"emails.certificate.footer": "您的上一個憑證將會在第一次失敗的 30 天後失效。我們強烈建議您調查這件事情,否則您的域名將會無法進行有效的 SSL 通訊。",
"emails.certificate.thanks": "謝謝",
"emails.certificate.signature": "{{project}} 團隊",
"locale.country.unknown": "未知",
"countries.af": "阿富汗",
"countries.ao": "安哥拉",
"countries.al": "阿爾巴尼亞",
"countries.ad": "安道爾",
"countries.ae": "阿拉伯聯合大公國",
"countries.ae": "阿拉伯聯合酋長國",
"countries.ar": "阿根廷",
"countries.am": "亞美尼亞",
"countries.ag": "安地卡及巴布達",
"countries.au": "澳",
"countries.ag": "安提瓜和巴布達",
"countries.au": "澳大利亞",
"countries.at": "奧地利",
"countries.az": "塞拜",
"countries.bi": "蒲隆地",
"countries.az": "塞拜",
"countries.bi": "布隆迪",
"countries.be": "比利時",
"countries.bj": "貝",
"countries.bf": "布納法索",
"countries.bd": "孟加拉",
"countries.bj": "貝",
"countries.bf": "布納法索",
"countries.bd": "孟加拉",
"countries.bg": "保加利亞",
"countries.bh": "巴林",
"countries.bs": "巴哈馬",
"countries.ba": "波士尼亞與赫塞哥維納",
"countries.by": "白羅斯",
"countries.bz": "貝里斯",
"countries.ba": "波",
"countries.by": "白羅斯",
"countries.bz": "伯利茲",
"countries.bo": "玻利維亞",
"countries.br": "巴西",
"countries.bb": "巴貝多",
"countries.bn": "萊",
"countries.bb": "巴巴多斯",
"countries.bn": "萊",
"countries.bt": "不丹",
"countries.bw": "波札那",
"countries.bw": "博茨瓦納",
"countries.cf": "中非共和國",
"countries.ca": "加拿大",
"countries.ch": "瑞士",
@@ -72,42 +66,42 @@
"countries.cd": "剛果民主共和國",
"countries.cg": "剛果共和國",
"countries.co": "哥倫比亞",
"countries.km": "摩",
"countries.cv": "維德角",
"countries.cr": "哥斯黎加",
"countries.km": "摩",
"countries.cv": "佛得角",
"countries.cr": "哥斯黎加",
"countries.cu": "古巴",
"countries.cy": "賽普勒斯",
"countries.cy": "塞浦路斯",
"countries.cz": "捷克",
"countries.de": "德國",
"countries.dj": "吉布",
"countries.dj": "吉布",
"countries.dm": "多米尼克",
"countries.dk": "丹麥",
"countries.do": "多明尼加共和國",
"countries.dz": "阿爾及利亞",
"countries.ec": "厄瓜多",
"countries.ec": "厄瓜多",
"countries.eg": "埃及",
"countries.er": "厄利垂亞",
"countries.er": "厄立特裏亞",
"countries.es": "西班牙",
"countries.ee": "愛沙尼亞",
"countries.et": "衣索比亞",
"countries.et": "埃塞俄比亞",
"countries.fi": "芬蘭",
"countries.fj": "斐濟",
"countries.fr": "法國",
"countries.fm": "密克羅尼西亞",
"countries.ga": "加",
"countries.ga": "加",
"countries.gb": "英國",
"countries.ge": "喬治亞",
"countries.gh": "納",
"countries.ge": "格魯吉亞",
"countries.gh": "納",
"countries.gn": "幾內亞",
"countries.gm": "比亞",
"countries.gw": "幾內亞比",
"countries.gm": "比亞",
"countries.gw": "幾內亞比",
"countries.gq": "赤道幾內亞",
"countries.gr": "希臘",
"countries.gd": "格瑞那達",
"countries.gt": "地馬拉",
"countries.gy": "亞那",
"countries.hn": "都拉斯",
"countries.hr": "克羅埃西亞",
"countries.gd": "格林納達",
"countries.gt": "地馬拉",
"countries.gy": "亞那",
"countries.hn": "都拉斯",
"countries.hr": "克羅亞",
"countries.ht": "海地",
"countries.hu": "匈牙利",
"countries.id": "印度尼西亞",
@@ -117,26 +111,26 @@
"countries.iq": "伊拉克",
"countries.is": "冰島",
"countries.il": "以色列",
"countries.it": "大利",
"countries.it": "大利",
"countries.jm": "牙買加",
"countries.jo": "約旦",
"countries.jp": "日本",
"countries.kz": "哈薩克",
"countries.ke": "肯亞",
"countries.kg": "吉爾吉斯",
"countries.kz": "哈薩克斯坦",
"countries.ke": "肯亞",
"countries.kg": "吉爾吉斯斯坦",
"countries.kh": "柬埔寨",
"countries.ki": "吉里巴斯",
"countries.kn": "聖克里斯多福及尼維斯",
"countries.ki": "基裏巴斯",
"countries.kn": "聖基茨和尼維斯",
"countries.kr": "韓國",
"countries.kw": "科威特",
"countries.la": "寮國",
"countries.la": "老撾",
"countries.lb": "黎巴嫩",
"countries.lr": "賴比瑞亞",
"countries.lr": "利比裏亞",
"countries.ly": "利比亞",
"countries.lc": "聖西亞",
"countries.li": "列支敦登",
"countries.lk": "斯蘭卡",
"countries.ls": "索托",
"countries.lc": "聖西亞",
"countries.li": "列支敦登",
"countries.lk": "斯蘭卡",
"countries.ls": "索托",
"countries.lt": "立陶宛",
"countries.lu": "盧森堡",
"countries.lv": "拉脫維亞",
@@ -144,90 +138,90 @@
"countries.mc": "摩納哥",
"countries.md": "摩爾多瓦",
"countries.mg": "馬達加斯加",
"countries.mv": "馬爾夫",
"countries.mv": "馬爾夫",
"countries.mx": "墨西哥",
"countries.mh": "馬紹爾群島",
"countries.mk": "馬其頓共和國",
"countries.ml": "馬",
"countries.mt": "馬他",
"countries.ml": "馬",
"countries.mt": "馬他",
"countries.mm": "緬甸",
"countries.me": "蒙特內哥羅",
"countries.me": "黑山",
"countries.mn": "蒙古",
"countries.mz": "莫比克",
"countries.mr": "茅利塔尼亞",
"countries.mu": "模里西斯",
"countries.mw": "馬拉",
"countries.mz": "莫比克",
"countries.mr": "毛裏塔尼亞",
"countries.mu": "毛裏求斯",
"countries.mw": "馬拉",
"countries.my": "馬來西亞",
"countries.na": "納米比亞",
"countries.ne": "尼日",
"countries.ng": "奈及利亞",
"countries.ne": "尼日",
"countries.ng": "尼日利亞",
"countries.ni": "尼加拉瓜",
"countries.nl": "荷蘭",
"countries.no": "挪威",
"countries.np": "尼泊爾",
"countries.nr": "魯",
"countries.nz": "西蘭",
"countries.nr": "魯",
"countries.nz": "西蘭",
"countries.om": "阿曼",
"countries.pk": "巴基斯坦",
"countries.pa": "巴拿馬",
"countries.pe": "秘魯",
"countries.ph": "菲律賓",
"countries.pw": "帛琉",
"countries.pg": "巴布亞幾內亞",
"countries.pw": "帕勞",
"countries.pg": "巴布亞幾內亞",
"countries.pl": "波蘭",
"countries.kp": "北",
"countries.kp": "北朝鮮",
"countries.pt": "葡萄牙",
"countries.py": "巴拉圭",
"countries.qa": "卡",
"countries.qa": "卡塔爾",
"countries.ro": "羅馬尼亞",
"countries.ru": "俄羅斯",
"countries.rw": "盧達",
"countries.sa": "沙烏地阿拉伯",
"countries.rw": "盧達",
"countries.sa": "沙阿拉伯",
"countries.sd": "蘇丹",
"countries.sn": "塞內加爾",
"countries.sg": "新加坡",
"countries.sb": "羅門群島",
"countries.sl": "獅子山",
"countries.sb": "羅門群島",
"countries.sl": "塞拉利昂",
"countries.sv": "薩爾瓦多",
"countries.sm": "聖馬諾",
"countries.so": "索馬利亞",
"countries.sm": "聖馬諾",
"countries.so": "索馬",
"countries.rs": "塞爾維亞",
"countries.ss": "南蘇丹",
"countries.st": "聖多美普林西比",
"countries.sr": "蘇南",
"countries.st": "聖多美普林西比",
"countries.sr": "蘇南",
"countries.sk": "斯洛伐克",
"countries.si": "斯洛尼亞",
"countries.si": "斯洛尼亞",
"countries.se": "瑞典",
"countries.sz": "史瓦帝尼",
"countries.sc": "塞爾",
"countries.sz": "斯威士蘭",
"countries.sc": "塞爾",
"countries.sy": "敘利亞",
"countries.td": "查德",
"countries.td": "乍得",
"countries.tg": "多哥",
"countries.th": "泰國",
"countries.tj": "塔吉克",
"countries.tm": "土庫曼",
"countries.tj": "塔吉克斯坦",
"countries.tm": "土庫曼斯坦",
"countries.tl": "東帝汶",
"countries.to": "加",
"countries.tt": "千里達及托巴哥",
"countries.tn": "突尼西亞",
"countries.to": "加",
"countries.tt": "特立尼達和多巴哥",
"countries.tn": "突尼",
"countries.tr": "土耳其",
"countries.tv": "吐瓦魯",
"countries.tz": "坦尼亞",
"countries.ug": "烏達",
"countries.tv": "圖瓦盧",
"countries.tz": "坦尼亞",
"countries.ug": "烏達",
"countries.ua": "烏克蘭",
"countries.uy": "烏拉圭",
"countries.us": "美國",
"countries.uz": "烏茲別克",
"countries.uz": "烏茲別克",
"countries.va": "梵蒂岡",
"countries.vc": "聖文森及格瑞那丁",
"countries.vc": "聖文森特和格林納丁斯",
"countries.ve": "委內瑞拉",
"countries.vn": "越南",
"countries.vu": "萬那杜",
"countries.vu": "瓦努阿圖",
"countries.ws": "薩摩亞",
"countries.ye": "門",
"countries.ye": "門",
"countries.za": "南非",
"countries.zm": "比亞",
"countries.zw": "辛巴威",
"countries.zm": "比亞",
"countries.zw": "津巴布韋",
"continents.af": "非洲",
"continents.an": "南極洲",
"continents.as": "亞洲",
@@ -235,4 +229,4 @@
"continents.na": "北美洲",
"continents.oc": "大洋洲",
"continents.sa": "南美洲"
}
}
+42 -103
View File
@@ -11,11 +11,11 @@ return [
'description' => 'Client libraries for integrating with Appwrite to build client-based applications and websites. Read the [getting started for web](/docs/getting-started-for-web) or [getting started for Flutter](/docs/getting-started-for-flutter) tutorials to start building your first application.',
'enabled' => true,
'beta' => false,
'sdks' => [
'languages' => [ // TODO change key to 'sdks'
[
'key' => 'web',
'name' => 'Web',
'version' => '11.0.0',
'version' => '9.0.1',
'url' => 'https://github.com/appwrite/sdk-for-web',
'package' => 'https://www.npmjs.com/package/appwrite',
'enabled' => true,
@@ -63,7 +63,7 @@ return [
[
'key' => 'flutter',
'name' => 'Flutter',
'version' => '9.0.0',
'version' => '6.0.0',
'url' => 'https://github.com/appwrite/sdk-for-flutter',
'package' => 'https://pub.dev/packages/appwrite',
'enabled' => true,
@@ -81,11 +81,11 @@ return [
[
'key' => 'apple',
'name' => 'Apple',
'version' => '2.0.0',
'version' => '0.6.0',
'url' => 'https://github.com/appwrite/sdk-for-apple',
'package' => 'https://github.com/appwrite/sdk-for-apple',
'enabled' => true,
'beta' => false,
'beta' => true,
'dev' => false,
'hidden' => false,
'family' => APP_PLATFORM_CLIENT,
@@ -116,11 +116,11 @@ return [
[
'key' => 'android',
'name' => 'Android',
'version' => '2.0.0',
'version' => '0.7.0',
'url' => 'https://github.com/appwrite/sdk-for-android',
'package' => 'https://search.maven.org/artifact/io.appwrite/sdk-for-android',
'enabled' => true,
'beta' => false,
'beta' => true,
'dev' => false,
'hidden' => false,
'family' => APP_PLATFORM_CLIENT,
@@ -135,44 +135,21 @@ return [
'Java' => 'java',
],
],
[
'key' => 'graphql',
'name' => 'GraphQL',
'version' => 'October 2021',
'url' => '',
'package' => '',
'enabled' => true,
'beta' => false,
'dev' => false,
'hidden' => true,
'family' => APP_PLATFORM_CLIENT,
'prism' => 'graphql',
'source' => \realpath(__DIR__ . '/../sdks/client-graphql'),
'gitUrl' => '',
'gitRepoName' => '',
'gitUserName' => '',
'gitBranch' => '',
'isSDK' => false,
],
[
'key' => 'rest',
'name' => 'REST',
'version' => '',
'url' => '',
'package' => '',
'enabled' => true,
'beta' => false,
'dev' => false,
'hidden' => true,
'family' => APP_PLATFORM_CLIENT,
'prism' => 'http',
'source' => \realpath(__DIR__ . '/../sdks/client-rest'),
'gitUrl' => '',
'gitRepoName' => '',
'gitUserName' => '',
'gitBranch' => '',
'isSDK' => false,
],
// [
// 'key' => 'java',
// 'name' => 'Java',
// 'url' => '',
// 'enabled' => false,
// 'beta' => false,
// 'dev' => false,
// 'hidden' => false,
// 'family' => APP_PLATFORM_CLIENT,
// 'prism' => 'java',
// 'source' => false,
// 'gitUrl' => 'git@github.com:appwrite/sdk-for-java.git',
// 'gitRepoName' => 'sdk-for-java',
// 'gitUserName' => 'appwrite',
// ],
],
],
@@ -181,11 +158,11 @@ return [
'name' => 'Console',
'enabled' => false,
'beta' => false,
'sdks' => [
'languages' => [
[
'key' => 'web',
'name' => 'Console',
'version' => '0.1.0',
'version' => '6.0.0',
'url' => 'https://github.com/appwrite/sdk-for-console',
'package' => '',
'enabled' => true,
@@ -193,17 +170,17 @@ return [
'dev' => false,
'hidden' => true,
'family' => APP_PLATFORM_CONSOLE,
'prism' => 'javascript',
'prism' => 'console',
'source' => \realpath(__DIR__ . '/../sdks/console-web'),
'gitUrl' => 'git@github.com:appwrite/sdk-for-console.git',
'gitBranch' => 'main',
'gitUrl' => null,
'gitBranch' => null,
'gitRepoName' => 'sdk-for-console',
'gitUserName' => 'appwrite',
],
[
'key' => 'cli',
'name' => 'Command Line',
'version' => '2.0.0',
'version' => '0.18.1',
'url' => 'https://github.com/appwrite/sdk-for-cli',
'package' => 'https://www.npmjs.com/package/appwrite-cli',
'enabled' => true,
@@ -227,11 +204,11 @@ return [
'description' => 'Libraries for integrating with Appwrite to build server side integrations. Read the [getting started for server](/docs/getting-started-for-server) tutorial to start building your first server integration.',
'enabled' => true,
'beta' => false,
'sdks' => [
'languages' => [
[
'key' => 'nodejs',
'name' => 'Node.js',
'version' => '9.0.0',
'version' => '7.0.2',
'url' => 'https://github.com/appwrite/sdk-for-node',
'package' => 'https://www.npmjs.com/package/node-appwrite',
'enabled' => true,
@@ -249,7 +226,7 @@ return [
[
'key' => 'deno',
'name' => 'Deno',
'version' => '7.0.0',
'version' => '5.0.1',
'url' => 'https://github.com/appwrite/sdk-for-deno',
'package' => 'https://deno.land/x/appwrite',
'enabled' => true,
@@ -267,7 +244,7 @@ return [
[
'key' => 'php',
'name' => 'PHP',
'version' => '8.0.0',
'version' => '6.0.0',
'url' => 'https://github.com/appwrite/sdk-for-php',
'package' => 'https://packagist.org/packages/appwrite/appwrite',
'enabled' => true,
@@ -285,7 +262,7 @@ return [
[
'key' => 'python',
'name' => 'Python',
'version' => '2.0.0',
'version' => '0.10.0',
'url' => 'https://github.com/appwrite/sdk-for-python',
'package' => 'https://pypi.org/project/appwrite/',
'enabled' => true,
@@ -303,7 +280,7 @@ return [
[
'key' => 'ruby',
'name' => 'Ruby',
'version' => '8.0.0',
'version' => '6.0.0',
'url' => 'https://github.com/appwrite/sdk-for-ruby',
'package' => 'https://rubygems.org/gems/appwrite',
'enabled' => true,
@@ -321,7 +298,7 @@ return [
[
'key' => 'go',
'name' => 'Go',
'version' => '2.0.0',
'version' => '0.1.0',
'url' => 'https://github.com/appwrite/sdk-for-go',
'package' => '',
'enabled' => false,
@@ -339,7 +316,7 @@ return [
[
'key' => 'java',
'name' => 'Java',
'version' => '2.0.0',
'version' => '0.0.2',
'url' => 'https://github.com/appwrite/sdk-for-java',
'package' => '',
'enabled' => false,
@@ -357,7 +334,7 @@ return [
[
'key' => 'dotnet',
'name' => '.NET',
'version' => '2.0.0',
'version' => '0.4.0',
'url' => 'https://github.com/appwrite/sdk-for-dotnet',
'package' => 'https://www.nuget.org/packages/Appwrite',
'enabled' => false,
@@ -375,7 +352,7 @@ return [
[
'key' => 'dart',
'name' => 'Dart',
'version' => '8.0.0',
'version' => '6.0.0',
'url' => 'https://github.com/appwrite/sdk-for-dart',
'package' => 'https://pub.dev/packages/dart_appwrite',
'enabled' => true,
@@ -393,11 +370,11 @@ return [
[
'key' => 'kotlin',
'name' => 'Kotlin',
'version' => '2.0.0',
'version' => '0.6.0',
'url' => 'https://github.com/appwrite/sdk-for-kotlin',
'package' => 'https://search.maven.org/artifact/io.appwrite/sdk-for-kotlin',
'enabled' => true,
'beta' => false,
'beta' => true,
'dev' => false,
'hidden' => false,
'family' => APP_PLATFORM_SERVER,
@@ -415,11 +392,11 @@ return [
[
'key' => 'swift',
'name' => 'Swift',
'version' => '2.0.0',
'version' => '0.6.0',
'url' => 'https://github.com/appwrite/sdk-for-swift',
'package' => 'https://github.com/appwrite/sdk-for-swift',
'enabled' => true,
'beta' => false,
'beta' => true,
'dev' => false,
'hidden' => false,
'family' => APP_PLATFORM_SERVER,
@@ -430,44 +407,6 @@ return [
'gitUserName' => 'appwrite',
'gitBranch' => 'main',
],
[
'key' => 'graphql',
'name' => 'GraphQL',
'version' => 'October 2021',
'url' => '',
'package' => '',
'enabled' => true,
'beta' => false,
'dev' => false,
'hidden' => true,
'family' => APP_PLATFORM_SERVER,
'prism' => 'graphql',
'source' => \realpath(__DIR__ . '/../sdks/server-graphql'),
'gitUrl' => '',
'gitRepoName' => '',
'gitUserName' => '',
'gitBranch' => '',
'isSDK' => false,
],
[
'key' => 'rest',
'name' => 'REST',
'version' => '',
'url' => '',
'package' => '',
'enabled' => true,
'beta' => false,
'dev' => false,
'hidden' => true,
'family' => APP_PLATFORM_SERVER,
'prism' => 'http',
'source' => \realpath(__DIR__ . '/../sdks/server-rest'),
'gitUrl' => '',
'gitRepoName' => '',
'gitUserName' => '',
'gitBranch' => '',
'isSDK' => false,
],
],
],
];
+1 -41
View File
@@ -17,7 +17,7 @@ return [ // Ordered by ABC.
'icon' => 'icon-apple',
'enabled' => true,
'sandbox' => false,
'form' => 'apple.phtml', // Preparation for adding ability to customized OAuth UI forms, currently handled hardcoded.
'form' => 'apple.phtml', // Perperation for adding ability to customized OAuth UI forms, currently handled hardcoded.
'beta' => true,
'mock' => false,
],
@@ -31,16 +31,6 @@ return [ // Ordered by ABC.
'beta' => false,
'mock' => false,
],
'authentik' => [
'name' => 'Authentik',
'developers' => 'https://goauthentik.io/docs/',
'icon' => 'icon-authentik',
'enabled' => true,
'sandbox' => false,
'form' => 'authentik.phtml',
'beta' => false,
'mock' => false,
],
'autodesk' => [
'name' => 'Autodesk',
'developers' => 'https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/overview/',
@@ -101,16 +91,6 @@ return [ // Ordered by ABC.
'beta' => false,
'mock' => false,
],
'disqus' => [
'name' => 'Disqus',
'developers' => 'https://disqus.com/api/docs/auth/',
'icon' => 'icon-disqus',
'enabled' => true,
'sandbox' => false,
'form' => false,
'beta' => false,
'mock' => false,
],
'dropbox' => [
'name' => 'Dropbox',
'developers' => 'https://www.dropbox.com/developers/documentation',
@@ -121,16 +101,6 @@ return [ // Ordered by ABC.
'beta' => false,
'mock' => false,
],
'etsy' => [
'name' => 'Etsy',
'developers' => 'https://developers.etsy.com/',
'icon' => 'icon-etsy',
'enabled' => true,
'sandbox' => false,
'form' => false,
'beta' => false,
'mock' => false,
],
'facebook' => [
'name' => 'Facebook',
'developers' => 'https://developers.facebook.com/',
@@ -231,16 +201,6 @@ return [ // Ordered by ABC.
'beta' => false,
'mock' => false
],
'podio' => [
'name' => 'Podio',
'developers' => 'https://developers.podio.com/doc/oauth-authorization',
'icon' => 'icon-podio',
'enabled' => true,
'sandbox' => false,
'form' => false,
'beta' => false,
'mock' => false,
],
'salesforce' => [
'name' => 'Salesforce',
'developers' => 'https://developer.salesforce.com/docs/',
-9
View File
@@ -1,9 +0,0 @@
<?php
return [
'default' => [
'name' => 'Default',
'default' => true,
'disabled' => false,
]
];
+7 -13
View File
@@ -6,7 +6,6 @@ $member = [
'public',
'home',
'console',
'graphql',
'account',
'teams.read',
'teams.write',
@@ -23,7 +22,6 @@ $member = [
];
$admins = [
'graphql',
'teams.read',
'teams.write',
'documents.read',
@@ -54,24 +52,20 @@ $admins = [
];
return [
Auth::USER_ROLE_GUESTS => [
'label' => 'Guests',
Auth::USER_ROLE_GUEST => [
'label' => 'Guest',
'scopes' => [
'public',
'home',
'console',
'graphql',
'documents.read',
'documents.write',
'files.read',
'files.write',
'locale.read',
'avatars.read',
'execution.write',
],
],
Auth::USER_ROLE_USERS => [
'label' => 'Users',
Auth::USER_ROLE_MEMBER => [
'label' => 'Member',
'scopes' => \array_merge($member, []),
],
Auth::USER_ROLE_ADMIN => [
@@ -86,8 +80,8 @@ return [
'label' => 'Owner',
'scopes' => \array_merge($member, $admins, []),
],
Auth::USER_ROLE_APPS => [
'label' => 'Applications',
'scopes' => ['health.read', 'graphql'],
Auth::USER_ROLE_APP => [
'label' => 'Application',
'scopes' => ['health.read'],
],
];
+1 -1
View File
@@ -7,7 +7,7 @@
use Utopia\App;
use Appwrite\Runtimes\Runtimes;
$runtimes = new Runtimes('v2');
$runtimes = new Runtimes('v1');
$allowList = empty(App::getEnv('_APP_FUNCTIONS_RUNTIMES')) ? [] : \explode(',', App::getEnv('_APP_FUNCTIONS_RUNTIMES'));
+10 -23
View File
@@ -1,9 +1,9 @@
<?php
return [
'web/home' => [
'key' => 'web/home',
'name' => 'Home',
'/' => [
'key' => 'homepage',
'name' => 'Homepage',
'subtitle' => '',
'description' => '',
'controller' => 'web/home.php',
@@ -14,8 +14,8 @@ return [
'optional' => false,
'icon' => '',
],
'web/console' => [
'key' => 'web/console',
'console' => [
'key' => 'console',
'name' => 'Console',
'subtitle' => '',
'description' => '',
@@ -176,26 +176,13 @@ return [
'graphql' => [
'key' => 'graphql',
'name' => 'GraphQL',
'subtitle' => 'The GraphQL API allows you to query and mutate your Appwrite server using GraphQL.',
'description' => '/docs/services/graphql.md',
'subtitle' => 'Appwrite\'s GraphQL Endpoint',
'description' => 'GraphQL Endpoint',
'controller' => 'api/graphql.php',
'sdk' => true,
'docs' => true,
'docsUrl' => 'https://appwrite.io/docs/graphql',
'tests' => true,
'optional' => true,
'icon' => '/images/services/graphql.png',
],
'console' => [
'key' => 'console',
'name' => 'Console',
'subtitle' => 'The Console service allows you to interact with console relevant informations.',
'description' => '',
'controller' => 'api/console.php',
'sdk' => true,
'docs' => true,
'sdk' => false,
'docs' => false,
'docsUrl' => '',
'tests' => false,
'tests' => true,
'optional' => false,
'icon' => '',
],
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+9 -78
View File
@@ -170,31 +170,13 @@ return [
],
[
'name' => '_APP_USAGE_AGGREGATION_INTERVAL',
'description' => 'Interval value containing the number of seconds that the Appwrite usage process should wait before aggregating stats and syncing it to Database from TimeSeries data. The default value is 30 seconds. Reintroduced in 1.1.0.',
'introduction' => '1.1.0',
'description' => 'Interval value containing the number of seconds that the Appwrite usage process should wait before aggregating stats and syncing it to mariadb from InfluxDB. The default value is 30 seconds.',
'introduction' => '0.10.0',
'default' => '30',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_USAGE_TIMESERIES_INTERVAL',
'description' => 'Deprecated since 1.1.0 use _APP_USAGE_AGGREGATION_INTERVAL instead.',
'introduction' => '1.0.0',
'default' => '30',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_USAGE_DATABASE_INTERVAL',
'description' => 'Deprecated since 1.1.0 use _APP_USAGE_AGGREGATION_INTERVAL instead.',
'introduction' => '1.0.0',
'default' => '900',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_WORKER_PER_CORE',
'description' => 'Internal Worker per core for the API, Realtime and Executor containers. Can be configured to optimize performance.',
@@ -412,8 +394,8 @@ return [
'description' => '',
'variables' => [
[
'name' => '_APP_SMS_PROVIDER',
'description' => "Provider used for delivering SMS for Phone authentication. Use the following format: 'sms://[USER]:[SECRET]@[PROVIDER]'. \n\nAvailable providers are twilio, text-magic, telesign, msg91, and vonage.",
'name' => '_APP_PHONE_PROVIDER',
'description' => "Provider used for delivering SMS for Phone authentication. Use the following format: 'phone://[USER]:[SECRET]@[PROVIDER]'. \n\nAvailable providers are twilio, text-magic and telesign.",
'introduction' => '0.15.0',
'default' => '',
'required' => false,
@@ -421,7 +403,7 @@ return [
'filter' => ''
],
[
'name' => '_APP_SMS_FROM',
'name' => '_APP_PHONE_FROM',
'description' => 'Phone number used for sending out messages. Must start with a leading \'+\' and maximum of 15 digits without spaces (+123456789).',
'introduction' => '0.15.0',
'default' => '',
@@ -482,9 +464,9 @@ return [
],
[
'name' => '_APP_STORAGE_DEVICE',
'description' => 'Select default storage device. The default value is \'local\'. List of supported adapters are \'local\', \'s3\', \'dospaces\', \'backblaze\', \'linode\' and \'wasabi\'.',
'description' => 'Select default storage device. The default value is \'Local\'. List of supported adapters are \'Local\', \'S3\', \'DOSpaces\', \'Backblaze\', \'Linode\' and \'Wasabi\'.',
'introduction' => '0.13.0',
'default' => 'local',
'default' => 'Local',
'required' => false,
'question' => '',
],
@@ -764,7 +746,7 @@ return [
],
[
'name' => '_APP_FUNCTIONS_INACTIVE_THRESHOLD',
'description' => 'The minimum time a function must be inactive before it can be shut down and cleaned up. This feature is intended to clean up unused containers. Containers may remain active for longer than the interval before being shut down, as Appwrite only cleans up unused containers every hour. If no value is provided, the default is 60 seconds.',
'description' => 'The minimum time a function can be inactive before it\'s container is shutdown and put to sleep. The default value is 60 seconds',
'introduction' => '0.13.0',
'default' => '60',
'required' => false,
@@ -822,15 +804,6 @@ return [
'question' => '',
'filter' => ''
],
[
'name' => '_APP_MAINTENANCE_RETENTION_CACHE',
'description' => 'The maximum duration (in seconds) upto which to retain cached files. The default value is 2592000 seconds (30 days).',
'introduction' => '1.0.0',
'default' => '2592000',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_MAINTENANCE_RETENTION_EXECUTION',
'description' => 'The maximum duration (in seconds) upto which to retain execution logs. The default value is 1209600 seconds (14 days).',
@@ -857,49 +830,7 @@ return [
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_MAINTENANCE_RETENTION_USAGE_HOURLY',
'description' => 'The maximum duration (in seconds) upto which to retain hourly usage metrics. The default value is 8640000 seconds (100 days).',
'introduction' => '',
'default' => '8640000',
'required' => false,
'question' => '',
'filter' => ''
],
],
],
[
'category' => 'GraphQL',
'description' => '',
'variables' => [
[
'name' => '_APP_GRAPHQL_MAX_BATCH_SIZE',
'description' => 'Maximum number of batched queries per request. The default value is 10.',
'introduction' => '1.2.0',
'default' => '10',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_GRAPHQL_MAX_COMPLEXITY',
'description' => 'Maximum complexity of a GraphQL query. One field adds one to query complexity. Lists multiply the complexity by the number of items requested. The default value is 250.',
'introduction' => '1.2.0',
'default' => '250',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_GRAPHQL_MAX_DEPTH',
'description' => 'Maximum depth of a GraphQL query. One nested field level adds one to query depth. The default value is 3.',
'introduction' => '1.2.0',
'default' => '3',
'required' => false,
'question' => '',
'filter' => ''
],
]
],
],
];
Submodule app/console deleted from ac4181aea4
File diff suppressed because it is too large Load Diff
+111 -63
View File
@@ -1,12 +1,14 @@
<?php
use Appwrite\Extend\Exception;
use Utopia\Validator\URL;
use Appwrite\Network\Validator\URL;
use Appwrite\URL\URL as URLParse;
use Appwrite\Utopia\Response;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Utopia\App;
use Utopia\Cache\Adapter\Filesystem;
use Utopia\Cache\Cache;
use Utopia\Config\Config;
use Utopia\Database\Document;
use Utopia\Image\Image;
@@ -23,34 +25,56 @@ $avatarCallback = function (string $type, string $code, int $width, int $height,
$set = Config::getParam('avatar-' . $type, []);
if (empty($set)) {
throw new Exception(Exception::AVATAR_SET_NOT_FOUND);
throw new Exception('Avatar set not found', 404, Exception::AVATAR_SET_NOT_FOUND);
}
if (!\array_key_exists($code, $set)) {
throw new Exception(Exception::AVATAR_NOT_FOUND);
throw new Exception('Avatar not found', 404, Exception::AVATAR_NOT_FOUND);
}
if (!\extension_loaded('imagick')) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing');
throw new Exception('Imagick extension is missing', 500, Exception::GENERAL_SERVER_ERROR);
}
$output = 'png';
$date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT'; // 45 days cache
$key = \md5('/v1/avatars/' . $type . '/:code-' . $code . $width . $height . $quality . $output);
$path = $set[$code];
$type = 'png';
if (!\is_readable($path)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'File not readable in ' . $path);
throw new Exception('File not readable in ' . $path, 500, Exception::GENERAL_SERVER_ERROR);
}
$cache = new Cache(new Filesystem(APP_STORAGE_CACHE . '/app-0')); // Limit file number or size
$data = $cache->load($key, 60 * 60 * 24 * 30 * 3/* 3 months */);
if ($data) {
//$output = (empty($output)) ? $type : $output;
return $response
->setContentType('image/png')
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'hit')
->send($data);
}
$image = new Image(\file_get_contents($path));
$image->crop((int) $width, (int) $height);
$output = (empty($output)) ? $type : $output;
$data = $image->output($output, $quality);
$cache->save($key, $data);
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT')
->setContentType('image/png')
->file($data)
;
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'miss')
->send($data, null);
unset($image);
};
@@ -58,8 +82,6 @@ App::get('/v1/avatars/credit-cards/:code')
->desc('Get Credit Card Icon')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
->label('cache', true)
->label('cache.resource', 'avatar/credit-card')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'avatars')
->label('sdk.method', 'getCreditCard')
@@ -78,8 +100,6 @@ App::get('/v1/avatars/browsers/:code')
->desc('Get Browser Icon')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
->label('cache', true)
->label('cache.resource', 'avatar/browser')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'avatars')
->label('sdk.method', 'getBrowser')
@@ -98,8 +118,6 @@ App::get('/v1/avatars/flags/:code')
->desc('Get Country Flag')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
->label('cache', true)
->label('cache.resource', 'avatar/flag')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'avatars')
->label('sdk.method', 'getFlag')
@@ -118,8 +136,6 @@ App::get('/v1/avatars/image')
->desc('Get Image from URL')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
->label('cache', true)
->label('cache.resource', 'avatar/image')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'avatars')
->label('sdk.method', 'getImage')
@@ -135,33 +151,50 @@ App::get('/v1/avatars/image')
$quality = 80;
$output = 'png';
$date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT'; // 45 days cache
$key = \md5('/v2/avatars/images-' . $url . '-' . $width . '/' . $height . '/' . $quality);
$type = 'png';
$cache = new Cache(new Filesystem(APP_STORAGE_CACHE . '/app-0')); // Limit file number or size
$data = $cache->load($key, 60 * 60 * 24 * 7/* 1 week */);
if ($data) {
return $response
->setContentType('image/png')
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'hit')
->send($data);
}
if (!\extension_loaded('imagick')) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing');
throw new Exception('Imagick extension is missing', 500, Exception::GENERAL_SERVER_ERROR);
}
$fetch = @\file_get_contents($url, false);
if (!$fetch) {
throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND);
throw new Exception('Image not found', 404, Exception::AVATAR_IMAGE_NOT_FOUND);
}
try {
$image = new Image($fetch);
} catch (\Exception $exception) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unable to parse image');
throw new Exception('Unable to parse image', 500, Exception::GENERAL_SERVER_ERROR);
}
$image->crop((int) $width, (int) $height);
$output = (empty($output)) ? $type : $output;
$data = $image->output($output, $quality);
$cache->save($key, $data);
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT')
->setContentType('image/png')
->file($data)
;
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'miss')
->send($data);
unset($image);
});
@@ -169,8 +202,6 @@ App::get('/v1/avatars/favicon')
->desc('Get Favicon')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
->label('cache', true)
->label('cache.resource', 'avatar/favicon')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'avatars')
->label('sdk.method', 'getFavicon')
@@ -186,10 +217,22 @@ App::get('/v1/avatars/favicon')
$height = 56;
$quality = 80;
$output = 'png';
$date = \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT'; // 45 days cache
$key = \md5('/v2/avatars/favicon-' . $url);
$type = 'png';
$cache = new Cache(new Filesystem(APP_STORAGE_CACHE . '/app-0')); // Limit file number or size
$data = $cache->load($key, 60 * 60 * 24 * 30 * 3/* 3 months */);
if ($data) {
return $response
->setContentType('image/png')
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'hit')
->send($data);
}
if (!\extension_loaded('imagick')) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing');
throw new Exception('Imagick extension is missing', 500, Exception::GENERAL_SERVER_ERROR);
}
$curl = \curl_init();
@@ -211,7 +254,7 @@ App::get('/v1/avatars/favicon')
\curl_close($curl);
if (!$html) {
throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED);
throw new Exception('Failed to fetch remote URL', 404, Exception::AVATAR_REMOTE_URL_FAILED);
}
$doc = new DOMDocument();
@@ -242,8 +285,8 @@ App::get('/v1/avatars/favicon')
case 'jpeg':
$size = \explode('x', \strtolower($sizes));
$sizeWidth = (int) ($size[0] ?? 0);
$sizeHeight = (int) ($size[1] ?? 0);
$sizeWidth = (int) $size[0] ?? 0;
$sizeHeight = (int) $size[1] ?? 0;
if (($sizeWidth * $sizeHeight) >= $space) {
$space = $sizeWidth * $sizeHeight;
@@ -269,31 +312,40 @@ App::get('/v1/avatars/favicon')
$data = @\file_get_contents($outputHref, false);
if (empty($data) || (\mb_substr($data, 0, 5) === '<html') || \mb_substr($data, 0, 5) === '<!doc') {
throw new Exception(Exception::AVATAR_ICON_NOT_FOUND, 'Favicon not found');
throw new Exception('Favicon not found', 404, Exception::AVATAR_ICON_NOT_FOUND);
}
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT')
$cache->save($key, $data);
return $response
->setContentType('image/x-icon')
->file($data)
;
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'miss')
->send($data);
}
$fetch = @\file_get_contents($outputHref, false);
if (!$fetch) {
throw new Exception(Exception::AVATAR_ICON_NOT_FOUND);
throw new Exception('Icon not found', 404, Exception::AVATAR_ICON_NOT_FOUND);
}
$image = new Image($fetch);
$image->crop((int) $width, (int) $height);
$output = (empty($output)) ? $type : $output;
$data = $image->output($output, $quality);
$cache->save($key, $data);
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT')
->setContentType('image/png')
->file($data)
;
->addHeader('Expires', $date)
->addHeader('X-Appwrite-Cache', 'miss')
->send($data);
unset($image);
});
@@ -329,20 +381,19 @@ App::get('/v1/avatars/qr')
}
$image = new Image($qrcode->render($text));
$image->crop((int) $size, (int) $size);
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache
->setContentType('image/png')
->send($image->output('png', 9))
;
->send($image->output('png', 9));
});
App::get('/v1/avatars/initials')
->desc('Get User Initials')
->groups(['api', 'avatars'])
->label('scope', 'avatars.read')
->label('cache.resource', 'avatar/initials')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'avatars')
->label('sdk.method', 'getInitials')
@@ -353,20 +404,27 @@ App::get('/v1/avatars/initials')
->param('name', '', new Text(128), 'Full Name. When empty, current user name or email will be used. Max length: 128 chars.', true)
->param('width', 500, new Range(0, 2000), 'Image width. Pass an integer between 0 to 2000. Defaults to 100.', true)
->param('height', 500, new Range(0, 2000), 'Image height. Pass an integer between 0 to 2000. Defaults to 100.', true)
->param('color', '', new HexColor(), 'Changes text color. By default a random color will be picked and stay will persistent to the given name.', true)
->param('background', '', new HexColor(), 'Changes background color. By default a random color will be picked and stay will persistent to the given name.', true)
->inject('response')
->inject('user')
->action(function (string $name, int $width, int $height, string $background, Response $response, Document $user) {
->action(function (string $name, int $width, int $height, string $color, string $background, Response $response, Document $user) {
$themes = [
['background' => '#FFA1CE'], // Default (Pink)
['background' => '#FDC584'], // Orange
['background' => '#94DBD1'], // Green
['background' => '#A1C4FF'], // Blue
['background' => '#FFA1CE'], // Pink
['background' => '#CBB1FC'] // Purple
['color' => '#27005e', 'background' => '#e1d2f6'], // VIOLET
['color' => '#5e2700', 'background' => '#f3d9c6'], // ORANGE
['color' => '#006128', 'background' => '#c9f3c6'], // GREEN
['color' => '#580061', 'background' => '#f2d1f5'], // FUSCHIA
['color' => '#00365d', 'background' => '#c6e1f3'], // BLUE
['color' => '#00075c', 'background' => '#d2d5f6'], // INDIGO
['color' => '#610038', 'background' => '#f5d1e6'], // PINK
['color' => '#386100', 'background' => '#dcf1bd'], // LIME
['color' => '#615800', 'background' => '#f1ecba'], // YELLOW
['color' => '#610008', 'background' => '#f6d2d5'], // RED
];
$rand = \rand(0, \count($themes) - 1);
$name = (!empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', ''));
$words = \explode(' ', \strtoupper($name));
// if there is no space, try to split by `_` underscore
@@ -385,40 +443,30 @@ App::get('/v1/avatars/initials')
}
$rand = \substr($code, -1);
// Wrap rand value to avoid out of range
$rand = ($rand > \count($themes) - 1) ? $rand % \count($themes) : $rand;
$background = (!empty($background)) ? '#' . $background : $themes[$rand]['background'];
$color = (!empty($color)) ? '#' . $color : $themes[$rand]['color'];
$image = new \Imagick();
$punch = new \Imagick();
$draw = new \ImagickDraw();
$fontSize = \min($width, $height) / 2;
$punch->newImage($width, $height, 'transparent');
$draw->setFont(__DIR__ . "/../../../public/fonts/poppins-v9-latin-500.ttf");
$image->setFont(__DIR__ . "/../../../public/fonts/poppins-v9-latin-500.ttf");
$draw->setFont(__DIR__ . "/../../assets/fonts/poppins-v9-latin-500.ttf");
$image->setFont(__DIR__ . "/../../assets/fonts/poppins-v9-latin-500.ttf");
$draw->setFillColor(new ImagickPixel('black'));
$draw->setFillColor(new \ImagickPixel($color));
$draw->setFontSize($fontSize);
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
$draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials);
$punch->drawImage($draw);
$punch->negateImage(true, Imagick::CHANNEL_ALPHA);
$image->newImage($width, $height, $background);
$image->setImageFormat("png");
$image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0);
$image->drawImage($draw);
//$image->setImageCompressionQuality(9 - round(($quality / 100) * 9));
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache
->setContentType('image/png')
->file($image->getImageBlob())
;
->send($image->getImageBlob());
});
-40
View File
@@ -1,40 +0,0 @@
<?php
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Database\Document;
App::init()
->groups(['console'])
->inject('project')
->action(function (Document $project) {
if ($project->getId() !== 'console') {
throw new Exception(Exception::GENERAL_ACCESS_FORBIDDEN);
}
});
App::get('/v1/console/variables')
->desc('Get Variables')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
->label('sdk.auth', [APP_AUTH_TYPE_ADMIN])
->label('sdk.namespace', 'console')
->label('sdk.method', 'variables')
->label('sdk.description', '/docs/references/console/variables.md')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_CONSOLE_VARIABLES)
->inject('response')
->action(function (Response $response) {
$variables = new Document([
'_APP_DOMAIN_TARGET' => App::getEnv('_APP_DOMAIN_TARGET'),
'_APP_STORAGE_LIMIT' => +App::getEnv('_APP_STORAGE_LIMIT'),
'_APP_FUNCTIONS_SIZE_LIMIT' => +App::getEnv('_APP_FUNCTIONS_SIZE_LIMIT'),
'_APP_USAGE_STATS' => App::getEnv('_APP_USAGE_STATS'),
]);
$response->dynamic($variables, Response::MODEL_CONSOLE_VARIABLES);
});
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+15 -288
View File
@@ -1,297 +1,24 @@
<?php
/**
* TODO:
* 1. Map all objects, object-params, object-fields
* 2. Parse GraphQL request payload (use: https://github.com/webonyx/graphql-php)
* 3. Route request to relevant controllers (of REST API?) / resolvers and aggergate data
* 4. Handle errors if any
* 5. Returen JSON response
* 6. Write tests!
*/
use Appwrite\Extend\Exception;
use Appwrite\GraphQL\Promises\Adapter;
use Appwrite\GraphQL\Schema;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use GraphQL\Error\DebugFlag;
use GraphQL\GraphQL;
use GraphQL\Type\Schema as GQLSchema;
use GraphQL\Validator\Rules\DisableIntrospection;
use GraphQL\Validator\Rules\QueryComplexity;
use GraphQL\Validator\Rules\QueryDepth;
use Swoole\Coroutine\WaitGroup;
use Utopia\App;
use Utopia\Database\Document;
use Utopia\Validator\JSON;
use Utopia\Validator\Text;
App::get('/v1/graphql')
->desc('GraphQL Endpoint')
->groups(['graphql'])
->label('scope', 'graphql')
->label('sdk.auth', [APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'graphql')
->label('sdk.hide', true)
->label('sdk.description', '/docs/references/graphql/get.md')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_ANY)
->label('abuse-limit', 60)
->label('abuse-time', 60)
->param('query', '', new Text(0, 0), 'The query to execute.')
->param('operationName', '', new Text(256), 'The name of the operation to execute.', true)
->param('variables', '', new Text(0), 'The JSON encoded variables to use in the query.', true)
->inject('request')
->inject('response')
->inject('schema')
->inject('promiseAdapter')
->action(function (string $query, string $operationName, string $variables, Request $request, Response $response, GQLSchema $schema, Adapter $promiseAdapter) {
$query = [
'query' => $query,
];
if (!empty($operationName)) {
$query['operationName'] = $operationName;
}
if (!empty($variables)) {
$query['variables'] = \json_decode($variables, true);
}
$output = execute($schema, $promiseAdapter, $query);
$response
->setStatusCode(Response::STATUS_CODE_OK)
->json($output);
});
App::post('/v1/graphql/mutation')
->desc('GraphQL Endpoint')
->groups(['graphql'])
->label('scope', 'graphql')
->label('sdk.auth', [APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'graphql')
->label('sdk.method', 'mutation')
->label('sdk.methodType', 'graphql')
->label('sdk.description', '/docs/references/graphql/post.md')
->label('sdk.parameters', [
'query' => ['default' => [], 'validator' => new JSON(), 'description' => 'The query or queries to execute.', 'optional' => false],
])
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_ANY)
->label('abuse-limit', 60)
->label('abuse-time', 60)
->inject('request')
->inject('response')
->inject('schema')
->inject('promiseAdapter')
->action(function (Request $request, Response $response, GQLSchema $schema, Adapter $promiseAdapter) {
$query = $request->getParams();
if ($request->getHeader('x-sdk-graphql') == 'true') {
$query = $query['query'];
}
$type = $request->getHeader('content-type');
if (\str_starts_with($type, 'application/graphql')) {
$query = parseGraphql($request);
}
if (\str_starts_with($type, 'multipart/form-data')) {
$query = parseMultipart($query, $request);
}
$output = execute($schema, $promiseAdapter, $query);
$response
->setStatusCode(Response::STATUS_CODE_OK)
->json($output);
});
App::post('/v1/graphql')
->desc('GraphQL Endpoint')
->groups(['graphql'])
->label('scope', 'graphql')
->label('sdk.auth', [APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'graphql')
->label('sdk.method', 'query')
->label('sdk.methodType', 'graphql')
->label('sdk.description', '/docs/references/graphql/post.md')
->label('sdk.parameters', [
'query' => ['default' => [], 'validator' => new JSON(), 'description' => 'The query or queries to execute.', 'optional' => false],
])
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_ANY)
->label('abuse-limit', 60)
->label('abuse-time', 60)
->inject('request')
->inject('response')
->inject('schema')
->inject('promiseAdapter')
->action(function (Request $request, Response $response, GQLSchema $schema, Adapter $promiseAdapter) {
$query = $request->getParams();
if ($request->getHeader('x-sdk-graphql') == 'true') {
$query = $query['query'];
}
$type = $request->getHeader('content-type');
if (\str_starts_with($type, 'application/graphql')) {
$query = parseGraphql($request);
}
if (\str_starts_with($type, 'multipart/form-data')) {
$query = parseMultipart($query, $request);
}
$output = execute($schema, $promiseAdapter, $query);
$response
->setStatusCode(Response::STATUS_CODE_OK)
->json($output);
});
/**
* Execute a GraphQL request
*
* @param GQLSchema $schema
* @param Adapter $promiseAdapter
* @param array $query
* @return array
* @throws Exception
*/
function execute(
GQLSchema $schema,
Adapter $promiseAdapter,
array $query
): array {
$maxBatchSize = App::getEnv('_APP_GRAPHQL_MAX_BATCH_SIZE', 10);
$maxComplexity = App::getEnv('_APP_GRAPHQL_MAX_COMPLEXITY', 250);
$maxDepth = App::getEnv('_APP_GRAPHQL_MAX_DEPTH', 3);
if (!empty($query) && !isset($query[0])) {
$query = [$query];
}
if (empty($query)) {
throw new Exception(Exception::GRAPHQL_NO_QUERY);
}
if (\count($query) > $maxBatchSize) {
throw new Exception(Exception::GRAPHQL_TOO_MANY_QUERIES);
}
foreach ($query as $item) {
if (empty($item['query'])) {
throw new Exception(Exception::GRAPHQL_NO_QUERY);
}
}
$flags = DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE;
$validations = GraphQL::getStandardValidationRules();
if (App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled') {
$validations[] = new DisableIntrospection();
$validations[] = new QueryComplexity($maxComplexity);
$validations[] = new QueryDepth($maxDepth);
}
if (App::getMode() === App::MODE_TYPE_PRODUCTION) {
$flags = DebugFlag::NONE;
}
$promises = [];
foreach ($query as $indexed) {
$promises[] = GraphQL::promiseToExecute(
$promiseAdapter,
$schema,
$indexed['query'],
variableValues: $indexed['variables'] ?? null,
operationName: $indexed['operationName'] ?? null,
validationRules: $validations
);
}
$output = [];
$wg = new WaitGroup();
$wg->add();
$promiseAdapter->all($promises)->then(
function (array $results) use (&$output, &$wg, $flags) {
try {
$output = processResult($results, $flags);
} finally {
$wg->done();
}
->groups(['api', 'graphql'])
->label('scope', 'public')
->action(
function () {
throw new Exception('GraphQL support is coming soon!', 502, Exception::GENERAL_SERVER_ERROR);
}
);
$wg->wait();
return $output;
}
/**
* Parse an "application/graphql" type request
*
* @param Request $request
* @return array
*/
function parseGraphql(Request $request): array
{
return ['query' => $request->getRawPayload()];
}
/**
* Parse an "multipart/form-data" type request
*
* @param array $query
* @param Request $request
* @return array
*/
function parseMultipart(array $query, Request $request): array
{
$operations = \json_decode($query['operations'], true);
$map = \json_decode($query['map'], true);
foreach ($map as $fileKey => $locations) {
foreach ($locations as $location) {
$items = &$operations;
foreach (\explode('.', $location) as $key) {
if (!isset($items[$key]) || !\is_array($items[$key])) {
$items[$key] = [];
}
$items = &$items[$key];
}
$items = $request->getFiles($fileKey);
}
}
$query['query'] = $operations['query'];
$query['variables'] = $operations['variables'];
unset($query['operations']);
unset($query['map']);
return $query;
}
/**
* Process an array of results for output.
*
* @param $result
* @param $debugFlags
* @return array
*/
function processResult($result, $debugFlags): array
{
// Only one query, return the result
if (!isset($result[1])) {
return $result[0]->toArray($debugFlags);
}
// Batched queries, return an array of results
return \array_map(
static function ($item) use ($debugFlags) {
return $item->toArray($debugFlags);
},
$result
);
}
App::shutdown()
->groups(['schema'])
->inject('project')
->action(function (Document $project) {
Schema::setDirty($project->getId());
});
+6 -6
View File
@@ -73,7 +73,7 @@ App::get('/v1/health/db')
$statement->execute();
} catch (Exception $_e) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Database is not available');
throw new Exception('Database is not available', 500, Exception::GENERAL_SERVER_ERROR);
}
$output = [
@@ -104,7 +104,7 @@ App::get('/v1/health/cache')
$redis = $utopia->getResource('cache');
if (!$redis->ping(true)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Cache is not available');
throw new Exception('Cache is not available', 500, Exception::GENERAL_SERVER_ERROR);
}
$output = [
@@ -160,7 +160,7 @@ App::get('/v1/health/time')
$diff = ($timestamp - \time());
if ($diff > $gap || $diff < ($gap * -1)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Server time gaps detected');
throw new Exception('Server time gaps detected', 500, Exception::GENERAL_SERVER_ERROR);
}
$output = [
@@ -267,11 +267,11 @@ App::get('/v1/health/storage/local')
$device = new Local($volume);
if (!\is_readable($device->getRoot())) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device ' . $key . ' dir is not readable');
throw new Exception('Device ' . $key . ' dir is not readable', 500, Exception::GENERAL_SERVER_ERROR);
}
if (!\is_writable($device->getRoot())) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device ' . $key . ' dir is not writable');
throw new Exception('Device ' . $key . ' dir is not writable', 500, Exception::GENERAL_SERVER_ERROR);
}
}
@@ -315,7 +315,7 @@ App::get('/v1/health/anti-virus')
$output['version'] = @$antivirus->version();
$output['status'] = (@$antivirus->ping()) ? 'pass' : 'fail';
} catch (\Exception $e) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Antivirus is not available');
throw new Exception('Antivirus is not available', 500, Exception::GENERAL_SERVER_ERROR);
}
}
+13 -26
View File
@@ -19,8 +19,6 @@ App::get('/v1/locale')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_LOCALE)
->label('sdk.offline.model', '/locale')
->label('sdk.offline.key', 'current')
->inject('request')
->inject('response')
->inject('locale')
@@ -42,6 +40,7 @@ App::get('/v1/locale')
$output['countryCode'] = $record['country']['iso_code'];
$output['country'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown'));
$output['continent'] = $locale->getText('continents.' . strtolower($record['continent']['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;
@@ -74,13 +73,11 @@ App::get('/v1/locale/countries')
->label('scope', 'locale.read')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'locale')
->label('sdk.method', 'listCountries')
->label('sdk.description', '/docs/references/locale/list-countries.md')
->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)
->label('sdk.offline.model', '/locale/countries')
->label('sdk.offline.response.key', 'code')
->inject('response')
->inject('locale')
->action(function (Response $response, Locale $locale) {
@@ -107,13 +104,11 @@ App::get('/v1/locale/countries/eu')
->label('scope', 'locale.read')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'locale')
->label('sdk.method', 'listCountriesEU')
->label('sdk.description', '/docs/references/locale/list-countries-eu.md')
->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)
->label('sdk.offline.model', '/locale/countries/eu')
->label('sdk.offline.response.key', 'code')
->inject('response')
->inject('locale')
->action(function (Response $response, Locale $locale) {
@@ -142,13 +137,11 @@ App::get('/v1/locale/countries/phones')
->label('scope', 'locale.read')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'locale')
->label('sdk.method', 'listCountriesPhones')
->label('sdk.description', '/docs/references/locale/list-countries-phones.md')
->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)
->label('sdk.offline.model', '/locale/countries/phones')
->label('sdk.offline.response.key', 'countryCode')
->inject('response')
->inject('locale')
->action(function (Response $response, Locale $locale) {
@@ -176,13 +169,11 @@ App::get('/v1/locale/continents')
->label('scope', 'locale.read')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'locale')
->label('sdk.method', 'listContinents')
->label('sdk.description', '/docs/references/locale/list-continents.md')
->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)
->label('sdk.offline.model', '/locale/continents')
->label('sdk.offline.response.key', 'code')
->inject('response')
->inject('locale')
->action(function (Response $response, Locale $locale) {
@@ -208,13 +199,11 @@ App::get('/v1/locale/currencies')
->label('scope', 'locale.read')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'locale')
->label('sdk.method', 'listCurrencies')
->label('sdk.description', '/docs/references/locale/list-currencies.md')
->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)
->label('sdk.offline.model', '/locale/currencies')
->label('sdk.offline.response.key', 'code')
->inject('response')
->action(function (Response $response) {
$list = Config::getParam('locale-currencies');
@@ -231,13 +220,11 @@ App::get('/v1/locale/languages')
->label('scope', 'locale.read')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'locale')
->label('sdk.method', 'listLanguages')
->label('sdk.description', '/docs/references/locale/list-languages.md')
->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)
->label('sdk.offline.model', '/locale/languages')
->label('sdk.offline.response.key', 'code')
->inject('response')
->action(function (Response $response) {
$list = Config::getParam('locale-languages');
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+38 -121
View File
@@ -4,18 +4,15 @@ global $utopia, $request, $response;
use Appwrite\Extend\Exception;
use Utopia\Database\Document;
use Utopia\Validator\Host;
use Appwrite\Network\Validator\Host;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;
use Utopia\App;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Integer;
use Utopia\Validator\Text;
use Utopia\Storage\Validator\File;
use Utopia\Validator\WhiteList;
use Utopia\Database\Helpers\ID;
use Utopia\Validator\Nullable;
App::get('/v1/mock/tests/foo')
->desc('Get Foo')
@@ -136,8 +133,6 @@ App::post('/v1/mock/tests/bar')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_MOCK)
->label('sdk.offline.model', '/mock/tests/bar')
->label('sdk.offline.key', '{required}')
->label('sdk.mock', true)
->param('required', '', new Text(100), 'Sample string param')
->param('default', '', new Integer(true), 'Sample numeric param')
@@ -199,35 +194,6 @@ App::delete('/v1/mock/tests/bar')
->action(function ($required, $default, $z) {
});
/** Endpoint to test if required headers are sent from the SDK */
App::get('/v1/mock/tests/general/headers')
->desc('Get headers')
->groups(['mock'])
->label('scope', 'public')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'general')
->label('sdk.method', 'headers')
->label('sdk.description', 'Return headers from the request')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.model', Response::MODEL_MOCK)
->label('sdk.mock', true)
->inject('request')
->inject('response')
->action(function (Request $request, Response $response) {
$res = [
'x-sdk-name' => $request->getHeader('x-sdk-name'),
'x-sdk-platform' => $request->getHeader('x-sdk-platform'),
'x-sdk-language' => $request->getHeader('x-sdk-language'),
'x-sdk-version' => $request->getHeader('x-sdk-version'),
];
$res = array_map(function ($key, $value) {
return $key . ': ' . $value;
}, array_keys($res), $res);
$res = implode("; ", $res);
$response->dynamic(new Document(['result' => $res]), Response::MODEL_MOCK);
});
App::get('/v1/mock/tests/general/download')
->desc('Download File')
->groups(['mock'])
@@ -248,7 +214,7 @@ App::get('/v1/mock/tests/general/download')
->addHeader('Content-Disposition', 'attachment; filename="test.txt"')
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache
->addHeader('X-Peak', \memory_get_peak_usage())
->send("GET:/v1/mock/tests/general/download:passed")
->send("Download test passed.")
;
});
@@ -268,7 +234,7 @@ App::post('/v1/mock/tests/general/upload')
->param('x', '', new Text(100), 'Sample string param')
->param('y', '', new Integer(true), 'Sample numeric param')
->param('z', null, new ArrayList(new Text(256), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Sample array param')
->param('file', [], new File(), 'Sample file param', skipValidation: true)
->param('file', [], new File(), 'Sample file param', false)
->inject('request')
->inject('response')
->action(function (string $x, int $y, array $z, mixed $file, Request $request, Response $response) {
@@ -287,36 +253,36 @@ App::post('/v1/mock/tests/general/upload')
$file['size'] = (\is_array($file['size'])) ? $file['size'][0] : $file['size'];
if (is_null($start) || is_null($end) || is_null($size)) {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid content-range header');
throw new Exception('Invalid content-range header', 400, Exception::GENERAL_MOCK);
}
if ($start > $end || $end > $size) {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid content-range header');
throw new Exception('Invalid content-range header', 400, Exception::GENERAL_MOCK);
}
if ($start === 0 && !empty($id)) {
throw new Exception(Exception::GENERAL_MOCK, 'First chunked request cannot have id header');
throw new Exception('First chunked request cannot have id header', 400, Exception::GENERAL_MOCK);
}
if ($start !== 0 && $id !== 'newfileid') {
throw new Exception(Exception::GENERAL_MOCK, 'All chunked request must have id header (except first)');
throw new Exception('All chunked request must have id header (except first)', 400, Exception::GENERAL_MOCK);
}
if ($end !== $size && $end - $start + 1 !== $chunkSize) {
throw new Exception(Exception::GENERAL_MOCK, 'Chunk size must be 5MB (except last chunk)');
throw new Exception('Chunk size must be 5MB (except last chunk)', 400, Exception::GENERAL_MOCK);
}
if ($end !== $size && $file['size'] !== $chunkSize) {
throw new Exception(Exception::GENERAL_MOCK, 'Wrong chunk size');
throw new Exception('Wrong chunk size', 400, Exception::GENERAL_MOCK);
}
if ($file['size'] > $chunkSize) {
throw new Exception(Exception::GENERAL_MOCK, 'Chunk size must be 5MB or less');
throw new Exception('Chunk size must be 5MB or less', 400, Exception::GENERAL_MOCK);
}
if ($end !== $size) {
$response->json([
'$id' => ID::custom('newfileid'),
'$id' => 'newfileid',
'chunksTotal' => $file['size'] / $chunkSize,
'chunksUploaded' => $start / $chunkSize
]);
@@ -327,15 +293,15 @@ App::post('/v1/mock/tests/general/upload')
$file['size'] = (\is_array($file['size'])) ? $file['size'][0] : $file['size'];
if ($file['name'] !== 'file.png') {
throw new Exception(Exception::GENERAL_MOCK, 'Wrong file name');
throw new Exception('Wrong file name', 400, Exception::GENERAL_MOCK);
}
if ($file['size'] !== 38756) {
throw new Exception(Exception::GENERAL_MOCK, 'Wrong file size');
throw new Exception('Wrong file size', 400, Exception::GENERAL_MOCK);
}
if (\md5(\file_get_contents($file['tmp_name'])) !== 'd80e7e6999a3eb2ae0d631a96fe135a4') {
throw new Exception(Exception::GENERAL_MOCK, 'Wrong file uploaded');
throw new Exception('Wrong file uploaded', 400, Exception::GENERAL_MOCK);
}
}
});
@@ -408,7 +374,7 @@ App::get('/v1/mock/tests/general/get-cookie')
->action(function (Request $request) {
if ($request->getCookie('cookieName', '') !== 'cookieValue') {
throw new Exception(Exception::GENERAL_MOCK, 'Missing cookie value');
throw new Exception('Missing cookie value', 400, Exception::GENERAL_MOCK);
}
});
@@ -429,50 +395,6 @@ App::get('/v1/mock/tests/general/empty')
$response->noContent();
});
App::post('/v1/mock/tests/general/nullable')
->desc('Nullable Test')
->groups(['mock'])
->label('scope', 'public')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'general')
->label('sdk.method', 'nullable')
->label('sdk.description', 'Mock a nullable parameter.')
->label('sdk.mock', true)
->param('required', '', new Text(100), 'Sample string param')
->param('nullable', '', new Nullable(new Text(100)), 'Sample string param')
->param('optional', '', new Text(100), 'Sample string param', true)
->action(function (string $required, string $nullable, ?string $optional) {
});
/** Endpoint to test if required headers are sent from the SDK */
App::get('/v1/mock/tests/general/headers')
->desc('Get headers')
->groups(['mock'])
->label('scope', 'public')
->label('sdk.auth', [APP_AUTH_TYPE_SESSION, APP_AUTH_TYPE_KEY, APP_AUTH_TYPE_JWT])
->label('sdk.namespace', 'general')
->label('sdk.method', 'headers')
->label('sdk.description', 'Return headers from the request')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.model', Response::MODEL_MOCK)
->label('sdk.mock', true)
->inject('request')
->inject('response')
->action(function (Request $request, Response $response) {
$res = [
'x-sdk-name' => $request->getHeader('x-sdk-name'),
'x-sdk-platform' => $request->getHeader('x-sdk-platform'),
'x-sdk-language' => $request->getHeader('x-sdk-language'),
'x-sdk-version' => $request->getHeader('x-sdk-version'),
];
$res = array_map(function ($key, $value) {
return $key . ': ' . $value;
}, array_keys($res), $res);
$res = implode("; ", $res);
$response->dynamic(new Document(['result' => $res]), Response::MODEL_MOCK);
});
App::get('/v1/mock/tests/general/400-error')
->desc('400 Error')
->groups(['mock'])
@@ -486,7 +408,7 @@ App::get('/v1/mock/tests/general/400-error')
->label('sdk.response.model', Response::MODEL_ERROR)
->label('sdk.mock', true)
->action(function () {
throw new Exception(Exception::GENERAL_MOCK, 'Mock 400 error');
throw new Exception('Mock 400 error', 400, Exception::GENERAL_MOCK);
});
App::get('/v1/mock/tests/general/500-error')
@@ -502,7 +424,7 @@ App::get('/v1/mock/tests/general/500-error')
->label('sdk.response.model', Response::MODEL_ERROR)
->label('sdk.mock', true)
->action(function () {
throw new Exception(Exception::GENERAL_MOCK, 'Mock 500 error', 500);
throw new Exception('Mock 500 error', 500, Exception::GENERAL_MOCK);
});
App::get('/v1/mock/tests/general/502-error')
@@ -558,11 +480,11 @@ App::get('/v1/mock/tests/general/oauth2/token')
->action(function (string $client_id, string $client_secret, string $grantType, string $redirectURI, string $code, string $refreshToken, Response $response) {
if ($client_id != '1') {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid client ID');
throw new Exception('Invalid client ID', 400, Exception::GENERAL_MOCK);
}
if ($client_secret != '123456') {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid client secret');
throw new Exception('Invalid client secret', 400, Exception::GENERAL_MOCK);
}
$responseJson = [
@@ -573,18 +495,18 @@ App::get('/v1/mock/tests/general/oauth2/token')
if ($grantType === 'authorization_code') {
if ($code !== 'abcdef') {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid token');
throw new Exception('Invalid token', 400, Exception::GENERAL_MOCK);
}
$response->json($responseJson);
} elseif ($grantType === 'refresh_token') {
if ($refreshToken !== 'tuvwxyz') {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid refresh token');
throw new Exception('Invalid refresh token', 400, Exception::GENERAL_MOCK);
}
$response->json($responseJson);
} else {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid grant type');
throw new Exception('Invalid grant type', 400, Exception::GENERAL_MOCK);
}
});
@@ -598,7 +520,7 @@ App::get('/v1/mock/tests/general/oauth2/user')
->action(function (string $token, Response $response) {
if ($token != '123456') {
throw new Exception(Exception::GENERAL_MOCK, 'Invalid token');
throw new Exception('Invalid token', 400, Exception::GENERAL_MOCK);
}
$response->json([
@@ -636,29 +558,24 @@ App::get('/v1/mock/tests/general/oauth2/failure')
]);
});
App::shutdown()
->groups(['mock'])
->inject('utopia')
->inject('response')
->inject('request')
->action(function (App $utopia, Response $response, Request $request) {
App::shutdown(function (App $utopia, Response $response, Request $request) {
$result = [];
$route = $utopia->match($request);
$path = APP_STORAGE_CACHE . '/tests.json';
$tests = (\file_exists($path)) ? \json_decode(\file_get_contents($path), true) : [];
$result = [];
$route = $utopia->match($request);
$path = APP_STORAGE_CACHE . '/tests.json';
$tests = (\file_exists($path)) ? \json_decode(\file_get_contents($path), true) : [];
if (!\is_array($tests)) {
throw new Exception(Exception::GENERAL_MOCK, 'Failed to read results', 500);
}
if (!\is_array($tests)) {
throw new Exception('Failed to read results', 500, Exception::GENERAL_MOCK);
}
$result[$route->getMethod() . ':' . $route->getPath()] = true;
$result[$route->getMethod() . ':' . $route->getPath()] = true;
$tests = \array_merge($tests, $result);
$tests = \array_merge($tests, $result);
if (!\file_put_contents($path, \json_encode($tests), LOCK_EX)) {
throw new Exception(Exception::GENERAL_MOCK, 'Failed to save results', 500);
}
if (!\file_put_contents($path, \json_encode($tests), LOCK_EX)) {
throw new Exception('Failed to save results', 500, Exception::GENERAL_MOCK);
}
$response->dynamic(new Document(['result' => $route->getMethod() . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK);
});
$response->dynamic(new Document(['result' => $route->getMethod() . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK);
}, ['utopia', 'response', 'request'], 'mock');
+204 -506
View File
@@ -5,550 +5,248 @@ use Appwrite\Event\Audit;
use Appwrite\Event\Database as EventDatabase;
use Appwrite\Event\Delete;
use Appwrite\Event\Event;
use Appwrite\Extend\Exception;
use Appwrite\Event\Mail;
use Appwrite\Messaging\Adapter\Realtime;
use Appwrite\Usage\Stats;
use Appwrite\Stats\Stats;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Request;
use Utopia\App;
use Appwrite\Extend\Exception;
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\Cache\Adapter\Filesystem;
use Utopia\Cache\Cache;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Registry\Registry;
$parseLabel = function (string $label, array $responsePayload, array $requestParams, Document $user) {
preg_match_all('/{(.*?)}/', $label, $matches);
foreach ($matches[1] ?? [] as $pos => $match) {
$find = $matches[0][$pos];
$parts = explode('.', $match);
App::init(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Mail $mails, Stats $usage, Delete $deletes, EventDatabase $database, Database $dbForProject, string $mode) {
if (count($parts) !== 2) {
throw new Exception('Too less or too many parts', 400, Exception::GENERAL_ARGUMENT_INVALID);
}
$route = $utopia->match($request);
$namespace = $parts[0] ?? '';
$replace = $parts[1] ?? '';
$params = match ($namespace) {
'user' => (array)$user,
'request' => $requestParams,
default => $responsePayload,
};
if (array_key_exists($replace, $params)) {
$label = \str_replace($find, $params[$replace], $label);
}
}
return $label;
};
$databaseListener = function (string $event, Document $document, Stats $usage) {
$multiplier = 1;
if ($event === Database::EVENT_DOCUMENT_DELETE) {
$multiplier = -1;
if ($project->isEmpty() && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope
throw new Exception('Missing or unknown project ID', 400, Exception::PROJECT_UNKNOWN);
}
$collection = $document->getCollection();
switch ($collection) {
case 'users':
$usage->setParam('users.{scope}.count.total', 1 * $multiplier);
break;
case 'databases':
$usage->setParam('databases.{scope}.count.total', 1 * $multiplier);
break;
case 'buckets':
$usage->setParam('buckets.{scope}.count.total', 1 * $multiplier);
break;
case 'deployments':
$usage->setParam('deployments.{scope}.storage.size', $document->getAttribute('size') * $multiplier);
break;
default:
if (strpos($collection, 'bucket_') === 0) {
$usage
->setParam('bucketId', $document->getAttribute('bucketId'))
->setParam('files.{scope}.storage.size', $document->getAttribute('sizeOriginal') * $multiplier)
->setParam('files.{scope}.count.total', 1 * $multiplier);
} elseif (strpos($collection, 'database_') === 0) {
$usage
->setParam('databaseId', $document->getAttribute('databaseId'));
if (strpos($collection, '_collection_') !== false) {
$usage
->setParam('collectionId', $document->getAttribute('$collectionId'))
->setParam('documents.{scope}.count.total', 1 * $multiplier);
} else {
$usage->setParam('collections.{scope}.count.total', 1 * $multiplier);
}
}
break;
}
};
/*
* Abuse Check
*/
$abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');
$timeLimitArray = [];
App::init()
->groups(['api'])
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('user')
->inject('events')
->inject('audits')
->inject('usage')
->inject('deletes')
->inject('database')
->inject('dbForProject')
->inject('mode')
->action(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, Database $dbForProject, string $mode) use ($databaseListener) {
$abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel;
$route = $utopia->match($request);
if ($project->isEmpty() && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope
throw new Exception(Exception::PROJECT_UNKNOWN);
}
/*
* Abuse Check
*/
$abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}');
$timeLimitArray = [];
$abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel;
foreach ($abuseKeyLabel as $abuseKey) {
$timeLimit = new TimeLimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForProject);
$timeLimit
foreach ($abuseKeyLabel as $abuseKey) {
$timeLimit = new TimeLimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForProject);
$timeLimit
->setParam('{userId}', $user->getId())
->setParam('{userAgent}', $request->getUserAgent(''))
->setParam('{ip}', $request->getIP())
->setParam('{url}', $request->getHostname() . $route->getPath())
->setParam('{method}', $request->getMethod());
$timeLimitArray[] = $timeLimit;
}
->setParam('{url}', $request->getHostname() . $route->getPath());
$timeLimitArray[] = $timeLimit;
}
$closestLimit = null;
$closestLimit = null;
$roles = Authorization::getRoles();
$isPrivilegedUser = Auth::isPrivilegedUser($roles);
$isAppUser = Auth::isAppUser($roles);
$roles = Authorization::getRoles();
$isPrivilegedUser = Auth::isPrivilegedUser($roles);
$isAppUser = Auth::isAppUser($roles);
foreach ($timeLimitArray as $timeLimit) {
foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys
if (!empty($value)) {
$timeLimit->setParam('{param-' . $key . '}', (\is_array($value)) ? \json_encode($value) : $value);
}
}
$abuse = new Abuse($timeLimit);
$remaining = $timeLimit->remaining();
$limit = $timeLimit->limit();
$time = (new \DateTime($timeLimit->time()))->getTimestamp() + $route->getLabel('abuse-time', 3600);
if ($limit && ($remaining < $closestLimit || is_null($closestLimit))) {
$closestLimit = $remaining;
$response
->addHeader('X-RateLimit-Limit', $limit)
->addHeader('X-RateLimit-Remaining', $remaining)
->addHeader('X-RateLimit-Reset', $time)
;
}
$enabled = App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled';
if (
$enabled // Abuse is enabled
&& !$isAppUser // User is not API key
&& !$isPrivilegedUser // User is not an admin
&& $abuse->check() // Route is rate-limited
) {
throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED);
foreach ($timeLimitArray as $timeLimit) {
foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys
if (!empty($value)) {
$timeLimit->setParam('{param-' . $key . '}', (\is_array($value)) ? \json_encode($value) : $value);
}
}
$abuse = new Abuse($timeLimit);
if ($timeLimit->limit() && ($timeLimit->remaining() < $closestLimit || is_null($closestLimit))) {
$closestLimit = $timeLimit->remaining();
$response
->addHeader('X-RateLimit-Limit', $timeLimit->limit())
->addHeader('X-RateLimit-Remaining', $timeLimit->remaining())
->addHeader('X-RateLimit-Reset', $timeLimit->time() + $route->getLabel('abuse-time', 3600))
;
}
if (
(App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled' // Route is rate-limited
&& $abuse->check()) // Abuse is not disabled
&& (!$isAppUser && !$isPrivilegedUser)
) { // User is not an admin or API key
throw new Exception('Too many requests', 429, Exception::GENERAL_RATE_LIMIT_EXCEEDED);
}
}
/*
* Background Jobs
*/
$events
->setEvent($route->getLabel('event', ''))
->setProject($project)
->setUser($user)
;
$mails
->setProject($project)
->setUser($user)
;
$audits
->setMode($mode)
->setUserAgent($request->getUserAgent(''))
->setIP($request->getIP())
->setEvent($route->getLabel('event', ''))
->setProject($project)
->setUser($user)
;
$usage
->setParam('projectId', $project->getId())
->setParam('httpRequest', 1)
->setParam('httpUrl', $request->getHostname() . $request->getURI())
->setParam('httpMethod', $request->getMethod())
->setParam('httpPath', $route->getPath())
->setParam('networkRequestSize', 0)
->setParam('networkResponseSize', 0)
->setParam('storage', 0)
;
$deletes->setProject($project);
$database->setProject($project);
}, ['utopia', 'request', 'response', 'project', 'user', 'events', 'audits', 'mails', 'usage', 'deletes', 'database', 'dbForProject', 'mode'], 'api');
App::init(function (App $utopia, Request $request, Document $project) {
$route = $utopia->match($request);
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
$isAppUser = Auth::isAppUser(Authorization::getRoles());
if ($isAppUser || $isPrivilegedUser) { // Skip limits for app and console devs
return;
}
$auths = $project->getAttribute('auths', []);
switch ($route->getLabel('auth.type', '')) {
case 'emailPassword':
if (($auths['emailPassword'] ?? true) === false) {
throw new Exception('Email / Password authentication is disabled for this project', 501, Exception::USER_AUTH_METHOD_UNSUPPORTED);
}
break;
case 'magic-url':
if ($project->getAttribute('usersAuthMagicURL', true) === false) {
throw new Exception('Magic URL authentication is disabled for this project', 501, Exception::USER_AUTH_METHOD_UNSUPPORTED);
}
break;
case 'anonymous':
if (($auths['anonymous'] ?? true) === false) {
throw new Exception('Anonymous authentication is disabled for this project', 501, Exception::USER_AUTH_METHOD_UNSUPPORTED);
}
break;
case 'invites':
if (($auths['invites'] ?? true) === false) {
throw new Exception('Invites authentication is disabled for this project', 501, Exception::USER_AUTH_METHOD_UNSUPPORTED);
}
break;
case 'jwt':
if (($auths['JWT'] ?? true) === false) {
throw new Exception('JWT authentication is disabled for this project', 501, Exception::USER_AUTH_METHOD_UNSUPPORTED);
}
break;
default:
throw new Exception('Unsupported authentication route', 501, Exception::USER_AUTH_METHOD_UNSUPPORTED);
break;
}
}, ['utopia', 'request', 'project'], 'auth');
App::shutdown(function (App $utopia, Request $request, Response $response, Document $project, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, string $mode, Database $dbForProject) {
if (!empty($events->getEvent())) {
if (empty($events->getPayload())) {
$events->setPayload($response->getPayload());
}
/**
* Trigger functions.
*/
$events
->setEvent($route->getLabel('event', ''))
->setProject($project)
->setUser($user);
->setClass(Event::FUNCTIONS_CLASS_NAME)
->setQueue(Event::FUNCTIONS_QUEUE_NAME)
->trigger();
$audits
->setMode($mode)
->setUserAgent($request->getUserAgent(''))
->setIP($request->getIP())
->setEvent($route->getLabel('audits.event', ''))
->setProject($project)
->setUser($user);
/**
* Trigger webhooks.
*/
$events
->setClass(Event::WEBHOOK_CLASS_NAME)
->setQueue(Event::WEBHOOK_QUEUE_NAME)
->trigger();
$usage
->setParam('projectInternalId', $project->getInternalId())
->setParam('projectId', $project->getId())
->setParam('project.{scope}.network.requests', 1)
->setParam('httpMethod', $request->getMethod())
->setParam('project.{scope}.network.inbound', 0)
->setParam('project.{scope}.network.outbound', 0);
/**
* Trigger realtime.
*/
if ($project->getId() !== 'console') {
$allEvents = Event::generateEvents($events->getEvent(), $events->getParams());
$payload = new Document($events->getPayload());
$deletes->setProject($project);
$database->setProject($project);
$db = $events->getContext('database');
$collection = $events->getContext('collection');
$bucket = $events->getContext('bucket');
$dbForProject->on(Database::EVENT_DOCUMENT_CREATE, fn ($event, Document $document) => $databaseListener($event, $document, $usage));
$dbForProject->on(Database::EVENT_DOCUMENT_DELETE, fn ($event, Document $document) => $databaseListener($event, $document, $usage));
$useCache = $route->getLabel('cache', false);
if ($useCache) {
$key = md5($request->getURI() . implode('*', $request->getParams())) . '*' . APP_CACHE_BUSTER;
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
$target = Realtime::fromPayload(
// Pass first, most verbose event pattern
event: $allEvents[0],
payload: $payload,
project: $project,
database: $db,
collection: $collection,
bucket: $bucket,
);
$timestamp = 60 * 60 * 24 * 30;
$data = $cache->load($key, $timestamp);
if (!empty($data)) {
$data = json_decode($data, true);
$parts = explode('/', $data['resourceType']);
$type = $parts[0] ?? null;
if ($type === 'bucket') {
$bucketId = $parts[1] ?? null;
$bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId));
if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) {
throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);
}
$fileSecurity = $bucket->getAttribute('fileSecurity', false);
$validator = new Authorization(Database::PERMISSION_READ);
$valid = $validator->isValid($bucket->getRead());
if (!$fileSecurity && !$valid) {
throw new Exception(Exception::USER_UNAUTHORIZED);
}
$parts = explode('/', $data['resource']);
$fileId = $parts[1] ?? null;
if ($fileSecurity && !$valid) {
$file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);
} else {
$file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId));
}
if ($file->isEmpty()) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
}
}
$response
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $timestamp) . ' GMT')
->addHeader('X-Appwrite-Cache', 'hit')
->setContentType($data['contentType'])
->send(base64_decode($data['payload']))
;
$route->setIsActive(false);
} else {
$response->addHeader('X-Appwrite-Cache', 'miss');
}
Realtime::send(
projectId: $target['projectId'] ?? $project->getId(),
payload: $events->getPayload(),
events: $allEvents,
channels: $target['channels'],
roles: $target['roles'],
options: [
'permissionsChanged' => $target['permissionsChanged'],
'userId' => $events->getParam('userId')
]
);
}
});
}
App::init()
->groups(['auth'])
->inject('utopia')
->inject('request')
->inject('project')
->action(function (App $utopia, Request $request, Document $project) {
$route = $utopia->match($request);
$isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles());
$isAppUser = Auth::isAppUser(Authorization::getRoles());
if ($isAppUser || $isPrivilegedUser) { // Skip limits for app and console devs
return;
if (!empty($audits->getResource())) {
foreach ($events->getParams() as $key => $value) {
$audits->setParam($key, $value);
}
$audits->trigger();
}
$auths = $project->getAttribute('auths', []);
switch ($route->getLabel('auth.type', '')) {
case 'emailPassword':
if (($auths['emailPassword'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Email / Password authentication is disabled for this project');
}
break;
if (!empty($deletes->getType())) {
$deletes->trigger();
}
case 'magic-url':
if ($project->getAttribute('usersAuthMagicURL', true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Magic URL authentication is disabled for this project');
}
break;
if (!empty($database->getType())) {
$database->trigger();
}
case 'anonymous':
if (($auths['anonymous'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Anonymous authentication is disabled for this project');
}
break;
case 'invites':
if (($auths['invites'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Invites authentication is disabled for this project');
}
break;
case 'jwt':
if (($auths['JWT'] ?? true) === false) {
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'JWT authentication is disabled for this project');
}
break;
default:
throw new Exception(Exception::USER_AUTH_METHOD_UNSUPPORTED, 'Unsupported authentication route');
break;
}
});
/**
* Limit user session
*
* Delete older sessions if the number of sessions have crossed
* the session limit set for the project
*/
App::shutdown()
->groups(['session'])
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('dbForProject')
->action(function (App $utopia, Request $request, Response $response, Document $project, Database $dbForProject) {
$sessionLimit = $project->getAttribute('auths', [])['maxSessions'] ?? APP_LIMIT_USER_SESSIONS_DEFAULT;
$session = $response->getPayload();
$userId = $session['userId'] ?? '';
if (empty($userId)) {
return;
}
$user = $dbForProject->getDocument('users', $userId);
if ($user->isEmpty()) {
return;
}
$sessions = $user->getAttribute('sessions', []);
$count = \count($sessions);
if ($count <= $sessionLimit) {
return;
}
for ($i = 0; $i < ($count - $sessionLimit); $i++) {
$session = array_shift($sessions);
$dbForProject->deleteDocument('sessions', $session->getId());
}
$dbForProject->deleteCachedDocument('users', $userId);
});
App::shutdown()
->groups(['api'])
->inject('utopia')
->inject('request')
->inject('response')
->inject('project')
->inject('events')
->inject('audits')
->inject('usage')
->inject('deletes')
->inject('database')
->inject('mode')
->inject('dbForProject')
->action(function (App $utopia, Request $request, Response $response, Document $project, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, string $mode, Database $dbForProject) use ($parseLabel) {
$responsePayload = $response->getPayload();
if (!empty($events->getEvent())) {
if (empty($events->getPayload())) {
$events->setPayload($responsePayload);
}
/**
* Trigger functions.
*/
$events
->setClass(Event::FUNCTIONS_CLASS_NAME)
->setQueue(Event::FUNCTIONS_QUEUE_NAME)
->trigger();
/**
* Trigger webhooks.
*/
$events
->setClass(Event::WEBHOOK_CLASS_NAME)
->setQueue(Event::WEBHOOK_QUEUE_NAME)
->trigger();
/**
* Trigger realtime.
*/
if ($project->getId() !== 'console') {
$allEvents = Event::generateEvents($events->getEvent(), $events->getParams());
$payload = new Document($events->getPayload());
$db = $events->getContext('database');
$collection = $events->getContext('collection');
$bucket = $events->getContext('bucket');
$target = Realtime::fromPayload(
// Pass first, most verbose event pattern
event: $allEvents[0],
payload: $payload,
project: $project,
database: $db,
collection: $collection,
bucket: $bucket,
);
Realtime::send(
projectId: $target['projectId'] ?? $project->getId(),
payload: $events->getPayload(),
events: $allEvents,
channels: $target['channels'],
roles: $target['roles'],
options: [
'permissionsChanged' => $target['permissionsChanged'],
'userId' => $events->getParam('userId')
]
);
}
}
$route = $utopia->match($request);
$requestParams = $route->getParamsValues();
$user = $audits->getUser();
/**
* Audit labels
*/
$pattern = $route->getLabel('audits.resource', null);
if (!empty($pattern)) {
$resource = $parseLabel($pattern, $responsePayload, $requestParams, $user);
if (!empty($resource) && $resource !== $pattern) {
$audits->setResource($resource);
}
}
$pattern = $route->getLabel('audits.userId', null);
if (!empty($pattern)) {
$userId = $parseLabel($pattern, $responsePayload, $requestParams, $user);
$user = $dbForProject->getDocument('users', $userId);
$audits->setUser($user);
}
if (!empty($audits->getResource()) && !empty($audits->getUser()->getId())) {
/**
* audits.payload is switched to default true
* in order to auto audit payload for all endpoints
*/
$pattern = $route->getLabel('audits.payload', true);
if (!empty($pattern)) {
$audits->setPayload($responsePayload);
}
foreach ($events->getParams() as $key => $value) {
$audits->setParam($key, $value);
}
$audits->trigger();
}
if (!empty($deletes->getType())) {
$deletes->trigger();
}
if (!empty($database->getType())) {
$database->trigger();
}
/**
* Cache label
*/
$useCache = $route->getLabel('cache', false);
if ($useCache) {
$resource = $resourceType = null;
$data = $response->getPayload();
if (!empty($data['payload'])) {
$pattern = $route->getLabel('cache.resource', null);
if (!empty($pattern)) {
$resource = $parseLabel($pattern, $responsePayload, $requestParams, $user);
}
$pattern = $route->getLabel('cache.resourceType', null);
if (!empty($pattern)) {
$resourceType = $parseLabel($pattern, $responsePayload, $requestParams, $user);
}
$key = md5($request->getURI() . implode('*', $request->getParams())) . '*' . APP_CACHE_BUSTER;
$data = json_encode([
'resourceType' => $resourceType,
'resource' => $resource,
'contentType' => $response->getContentType(),
'payload' => base64_encode($data['payload']),
]) ;
$signature = md5($data);
$cacheLog = $dbForProject->getDocument('cache', $key);
$accessedAt = $cacheLog->getAttribute('accessedAt', '');
$now = DateTime::now();
if ($cacheLog->isEmpty()) {
Authorization::skip(fn () => $dbForProject->createDocument('cache', new Document([
'$id' => $key,
'resource' => $resource,
'accessedAt' => $now,
'signature' => $signature,
])));
} elseif (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_CACHE_UPDATE)) > $accessedAt) {
$cacheLog->setAttribute('accessedAt', $now);
Authorization::skip(fn () => $dbForProject->updateDocument('cache', $cacheLog->getId(), $cacheLog));
}
if ($signature !== $cacheLog->getAttribute('signature')) {
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId())
);
$cache->save($key, $data);
}
}
}
if (
App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled'
&& $project->getId()
&& !empty($route->getLabel('sdk.namespace', null))
) { // Don't calculate console usage on admin mode
$metric = $route->getLabel('usage.metric', '');
$usageParams = $route->getLabel('usage.params', []);
if (!empty($metric)) {
$usage->setParam($metric, 1);
foreach ($usageParams as $param) {
$param = $parseLabel($param, $responsePayload, $requestParams, $user);
$parts = explode(':', $param);
if (count($parts) != 2) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Usage params not properly set');
}
$usage->setParam($parts[0], $parts[1]);
}
}
$fileSize = 0;
$file = $request->getFiles('file');
if (!empty($file)) {
$fileSize = (\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size'];
}
$usage
->setParam('project.{scope}.network.inbound', $request->getSize() + $fileSize)
->setParam('project.{scope}.network.outbound', $response->getSize())
->submit();
}
});
$route = $utopia->match($request);
if (
App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled'
&& $project->getId()
&& $mode !== APP_MODE_ADMIN // TODO: add check to make sure user is admin
&& !empty($route->getLabel('sdk.namespace', null))
) { // Don't calculate console usage on admin mode
$usage
->setParam('networkRequestSize', $request->getSize() + $usage->getParam('storage'))
->setParam('networkResponseSize', $response->getSize())
->submit();
}
}, ['utopia', 'request', 'response', 'project', 'events', 'audits', 'usage', 'deletes', 'database', 'mode', 'dbForProject'], 'api');
+59
View File
@@ -0,0 +1,59 @@
<?php
use Utopia\App;
use Utopia\Config\Config;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Request;
use Appwrite\Utopia\View;
App::init(function (App $utopia, Request $request, Response $response, View $layout) {
/* AJAX check */
if (!empty($request->getQuery('version', ''))) {
$layout->setPath(__DIR__ . '/../../views/layouts/empty.phtml');
}
$port = $request->getPort();
$protocol = $request->getProtocol();
$domain = $request->getHostname();
$layout
->setParam('title', APP_NAME)
->setParam('protocol', $protocol)
->setParam('domain', $domain)
->setParam('endpoint', $protocol . '://' . $domain . ($port != 80 && $port != 443 ? ':' . $port : ''))
->setParam('home', App::getEnv('_APP_HOME'))
->setParam('setup', App::getEnv('_APP_SETUP'))
->setParam('class', 'unknown')
->setParam('icon', '/images/favicon.png')
->setParam('roles', [
['type' => 'owner', 'label' => 'Owner'],
['type' => 'developer', 'label' => 'Developer'],
['type' => 'admin', 'label' => 'Admin'],
])
->setParam('runtimes', Config::getParam('runtimes'))
->setParam('mode', App::getMode())
;
$time = (60 * 60 * 24 * 45); // 45 days cache
$response
->addHeader('Cache-Control', 'public, max-age=' . $time)
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time) . ' GMT') // 45 days cache
->addHeader('X-Frame-Options', 'SAMEORIGIN') // Avoid console and homepage from showing in iframes
->addHeader('X-XSS-Protection', '1; mode=block; report=/v1/xss?url=' . \urlencode($request->getURI()))
->addHeader('X-UA-Compatible', 'IE=Edge') // Deny IE browsers from going into quirks mode
;
$route = $utopia->match($request);
$route->label('error', __DIR__ . '/../../views/general/error.phtml');
$scope = $route->getLabel('scope', '');
$layout
->setParam('version', App::getEnv('_APP_VERSION', 'UNKNOWN'))
->setParam('isDev', App::isDevelopment())
->setParam('class', $scope)
;
}, ['utopia', 'request', 'response', 'layout'], 'web');
+506 -10
View File
@@ -1,19 +1,515 @@
<?php
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\View;
use Utopia\App;
use Utopia\Config\Config;
use Utopia\Domains\Domain;
use Utopia\Database\Validator\UID;
use Utopia\Storage\Storage;
App::get('/console')
->alias('/')
->alias('/invite')
->alias('/login')
->alias('/recover')
->alias('/register')
->groups(['web'])
App::init(function (View $layout) {
$layout
->setParam('description', 'Appwrite Console allows you to easily manage, monitor, and control your entire backend API and tools.')
->setParam('analytics', 'UA-26264668-5')
;
}, ['layout'], 'console');
App::shutdown(function (Response $response, View $layout) {
$header = new View(__DIR__ . '/../../views/console/comps/header.phtml');
$footer = new View(__DIR__ . '/../../views/console/comps/footer.phtml');
$footer
->setParam('home', App::getEnv('_APP_HOME', ''))
->setParam('version', App::getEnv('_APP_VERSION', 'UNKNOWN'))
;
$layout
->setParam('header', [$header])
->setParam('footer', [$footer])
;
$response->html($layout->render());
}, ['response', 'layout'], 'console');
App::get('/error/:code')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'home')
->param('code', null, new \Utopia\Validator\Numeric(), 'Valid status code number', false)
->inject('layout')
->action(function (int $code, View $layout) {
$page = new View(__DIR__ . '/../../views/error.phtml');
$page
->setParam('code', $code)
;
$layout
->setParam('title', APP_NAME . ' - Error')
->setParam('body', $page);
});
App::get('/console')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/index.phtml');
$page
->setParam('home', App::getEnv('_APP_HOME', ''))
;
$layout
->setParam('title', APP_NAME . ' - Console')
->setParam('body', $page);
});
App::get('/console/account')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/account/index.phtml');
$cc = new View(__DIR__ . '/../../views/console/forms/credit-card.phtml');
$page
->setParam('cc', $cc)
;
$layout
->setParam('title', 'Account - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/console/notifications')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/v1/console/notifications/index.phtml');
$layout
->setParam('title', APP_NAME . ' - Notifications')
->setParam('body', $page);
});
App::get('/console/home')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/home/index.phtml');
$page
->setParam('usageStatsEnabled', App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled');
$layout
->setParam('title', APP_NAME . ' - Console')
->setParam('body', $page);
});
App::get('/console/settings')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', ''));
$page = new View(__DIR__ . '/../../views/console/settings/index.phtml');
$page->setParam('services', array_filter(Config::getParam('services'), fn($element) => $element['optional']))
->setParam('customDomainsEnabled', ($target->isKnown() && !$target->isTest()))
->setParam('customDomainsTarget', $target->get())
->setParam('smtpEnabled', (!empty(App::getEnv('_APP_SMTP_HOST'))))
;
$layout
->setParam('title', APP_NAME . ' - Settings')
->setParam('body', $page);
});
App::get('/console/webhooks')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/webhooks/index.phtml');
$page->setParam('events', Config::getParam('events', []));
$layout
->setParam('title', APP_NAME . ' - Webhooks')
->setParam('body', $page);
});
App::get('/console/webhooks/webhook')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->param('id', '', new UID(), 'Webhook unique ID.')
->inject('layout')
->action(function (string $id, View $layout) {
$page = new View(__DIR__ . '/../../views/console/webhooks/webhook.phtml');
$page
->setParam('events', Config::getParam('events', []))
->setParam('new', false)
;
$layout
->setParam('title', APP_NAME . ' - Webhooks')
->setParam('body', $page);
});
App::get('/console/webhooks/webhook/new')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/webhooks/webhook.phtml');
$page
->setParam('events', Config::getParam('events', []))
->setParam('new', true)
;
$layout
->setParam('title', APP_NAME . ' - Webhooks')
->setParam('body', $page);
});
App::get('/console/keys')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$scopes = array_keys(Config::getParam('scopes'));
$page = new View(__DIR__ . '/../../views/console/keys/index.phtml');
$page->setParam('scopes', $scopes);
$layout
->setParam('title', APP_NAME . ' - API Keys')
->setParam('body', $page);
});
App::get('/console/databases')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/databases/index.phtml');
$layout
->setParam('title', APP_NAME . ' - Database')
->setParam('body', $page);
});
App::get('/console/databases/database')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->param('id', '', new UID(), 'Database unique ID.')
->inject('response')
->action(function (Response $response) {
$fallback = file_get_contents(__DIR__ . '/../../../console/index.html');
$response->html($fallback);
->inject('layout')
->action(function (string $id, Response $response, View $layout) {
$logs = new View(__DIR__ . '/../../views/console/comps/logs.phtml');
$logs
->setParam('interval', App::getEnv('_APP_MAINTENANCE_RETENTION_AUDIT', 0))
->setParam('method', 'database.listLogs')
->setParam('params', [
'database-id' => '{{router.params.id}}',
])
;
$page = new View(__DIR__ . '/../../views/console/databases/database.phtml');
$page->setParam('logs', $logs);
$layout
->setParam('title', APP_NAME . ' - Database')
->setParam('body', $page)
;
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Expires', 0)
->addHeader('Pragma', 'no-cache')
;
});
App::get('/console/databases/collection')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->param('id', '', new UID(), 'Collection unique ID.')
->inject('response')
->inject('layout')
->action(function (string $id, Response $response, View $layout) {
$logs = new View(__DIR__ . '/../../views/console/comps/logs.phtml');
$logs
->setParam('interval', App::getEnv('_APP_MAINTENANCE_RETENTION_AUDIT', 0))
->setParam('method', 'databases.listCollectionLogs')
->setParam('params', [
'collection-id' => '{{router.params.id}}',
'database-id' => '{{router.params.databaseId}}'
])
;
$page = new View(__DIR__ . '/../../views/console/databases/collection.phtml');
$page->setParam('logs', $logs);
$layout
->setParam('title', APP_NAME . ' - Database Collection')
->setParam('body', $page)
;
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Expires', 0)
->addHeader('Pragma', 'no-cache')
;
});
App::get('/console/databases/document')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->param('databaseId', '', new UID(), 'Database unique ID.')
->param('collection', '', new UID(), 'Collection unique ID.')
->inject('layout')
->action(function (string $databaseId, string $collection, View $layout) {
$logs = new View(__DIR__ . '/../../views/console/comps/logs.phtml');
$logs
->setParam('interval', App::getEnv('_APP_MAINTENANCE_RETENTION_AUDIT', 0))
->setParam('method', 'databases.listDocumentLogs')
->setParam('params', [
'database-id' => '{{router.params.databaseId}}',
'collection-id' => '{{router.params.collection}}',
'document-id' => '{{router.params.id}}',
])
;
$page = new View(__DIR__ . '/../../views/console/databases/document.phtml');
$page
->setParam('new', false)
->setParam('database', $databaseId)
->setParam('collection', $collection)
->setParam('logs', $logs)
;
$layout
->setParam('title', APP_NAME . ' - Database Document')
->setParam('body', $page);
});
App::get('/console/databases/document/new')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->param('databaseId', '', new UID(), 'Database unique ID.')
->param('collection', '', new UID(), 'Collection unique ID.')
->inject('layout')
->action(function (string $databaseId, string $collection, View $layout) {
$page = new View(__DIR__ . '/../../views/console/databases/document.phtml');
$page
->setParam('new', true)
->setParam('database', $databaseId)
->setParam('collection', $collection)
->setParam('logs', new View())
;
$layout
->setParam('title', APP_NAME . ' - Database Document')
->setParam('body', $page);
});
App::get('/console/storage')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/storage/index.phtml');
$page
->setParam('home', App::getEnv('_APP_HOME', 0))
->setParam('fileLimit', App::getEnv('_APP_STORAGE_LIMIT', 0))
->setParam('fileLimitHuman', Storage::human(App::getEnv('_APP_STORAGE_LIMIT', 0)))
;
$layout
->setParam('title', APP_NAME . ' - Storage')
->setParam('body', $page);
});
App::get('/console/storage/bucket')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->param('id', '', new UID(), 'Bucket unique ID.')
->inject('response')
->inject('layout')
->action(function (string $id, Response $response, View $layout) {
$page = new View(__DIR__ . '/../../views/console/storage/bucket.phtml');
$page
->setParam('home', App::getEnv('_APP_HOME', 0))
->setParam('fileLimit', App::getEnv('_APP_STORAGE_LIMIT', 0))
->setParam('fileLimitHuman', Storage::human(App::getEnv('_APP_STORAGE_LIMIT', 0)))
;
$layout
->setParam('title', APP_NAME . ' - Storage Buckets')
->setParam('body', $page)
;
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Expires', 0)
->addHeader('Pragma', 'no-cache')
;
});
App::get('/console/users')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/users/index.phtml');
$page
->setParam('auth', Config::getParam('auth'))
->setParam('providers', Config::getParam('providers'))
->setParam('smtpEnabled', (!empty(App::getEnv('_APP_SMTP_HOST'))))
;
$layout
->setParam('title', APP_NAME . ' - Users')
->setParam('body', $page);
});
App::get('/console/users/user')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/users/user.phtml');
$layout
->setParam('title', APP_NAME . ' - User')
->setParam('body', $page);
});
App::get('/console/users/teams/team')
->groups(['web', 'console'])
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/users/team.phtml');
$layout
->setParam('title', APP_NAME . ' - Team')
->setParam('body', $page);
});
App::get('/console/functions')
->groups(['web', 'console'])
->desc('Platform console project functions')
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/functions/index.phtml');
$page
->setParam('runtimes', Config::getParam('runtimes'))
;
$layout
->setParam('title', APP_NAME . ' - Functions')
->setParam('body', $page);
});
App::get('/console/functions/function')
->groups(['web', 'console'])
->desc('Platform console project function')
->label('permission', 'public')
->label('scope', 'console')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/console/functions/function.phtml');
$page
->setParam('events', Config::getParam('events', []))
->setParam('fileLimit', App::getEnv('_APP_STORAGE_LIMIT', 0))
->setParam('fileLimitHuman', Storage::human(App::getEnv('_APP_STORAGE_LIMIT', 0)))
->setParam('timeout', (int) App::getEnv('_APP_FUNCTIONS_TIMEOUT', 900))
->setParam('usageStatsEnabled', App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled');
;
$layout
->setParam('title', APP_NAME . ' - Function')
->setParam('body', $page);
});
App::get('/console/version')
->groups(['web', 'console'])
->desc('Check for new version')
->label('permission', 'public')
->label('scope', 'console')
->inject('response')
->action(function ($response) {
try {
$version = \json_decode(@\file_get_contents(App::getEnv('_APP_HOME', 'http://localhost') . '/v1/health/version'), true);
if ($version && isset($version['version'])) {
return $response->json(['version' => $version['version']]);
} else {
throw new Exception('Failed to check for a newer version', 500, Exception::GENERAL_SERVER_ERROR);
}
} catch (\Throwable $th) {
throw new Exception('Failed to check for a newer version', 500, Exception::GENERAL_SERVER_ERROR);
}
});
+225 -1
View File
@@ -1,8 +1,231 @@
<?php
use Appwrite\Utopia\View;
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Config\Config;
use Utopia\Database\Database;
use Utopia\Database\Document;
App::init(function (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 $response, View $layout) {
$response->html($layout->render());
}, ['response', 'layout'], 'home');
App::get('/')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('response')
->inject('dbForConsole')
->inject('project')
->action(function (Response $response, Database $dbForConsole, Document $project) {
$response
->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->addHeader('Expires', 0)
->addHeader('Pragma', 'no-cache')
;
if ('console' === $project->getId() || $project->isEmpty()) {
$whitelistRoot = App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled');
if ($whitelistRoot !== 'disabled') {
$count = $dbForConsole->count('users', [], 1);
if ($count !== 0) {
return $response->redirect('/auth/signin');
}
}
}
$response->redirect('/auth/signup');
});
App::get('/auth/signin')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/signin.phtml');
$page
->setParam('root', App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled'))
;
$layout
->setParam('title', 'Sign In - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/auth/signup')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/signup.phtml');
$page
->setParam('root', App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled'))
;
$layout
->setParam('title', 'Sign Up - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/auth/recovery')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/recovery.phtml');
$page
->setParam('smtpEnabled', (!empty(App::getEnv('_APP_SMTP_HOST'))))
;
$layout
->setParam('title', 'Password Recovery - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/auth/confirm')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/confirm.phtml');
$layout
->setParam('title', 'Account Confirmation - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/auth/join')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/join.phtml');
$layout
->setParam('title', 'Invitation - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/auth/recovery/reset')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/recovery/reset.phtml');
$layout
->setParam('title', 'Password Reset - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/auth/oauth2/success')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/oauth2.phtml');
$layout
->setParam('title', APP_NAME)
->setParam('body', $page)
->setParam('header', [])
->setParam('footer', [])
;
});
App::get('/auth/magic-url')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/magicURL.phtml');
$layout
->setParam('title', APP_NAME)
->setParam('body', $page)
->setParam('header', [])
->setParam('footer', [])
;
});
App::get('/auth/oauth2/failure')
->groups(['web', 'home'])
->label('permission', 'public')
->label('scope', 'home')
->inject('layout')
->action(function (View $layout) {
$page = new View(__DIR__ . '/../../views/home/auth/oauth2.phtml');
$layout
->setParam('title', APP_NAME)
->setParam('body', $page)
->setParam('header', [])
->setParam('footer', [])
;
});
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)
->inject('layout')
->action(function (int $code, View $layout) {
$page = new View(__DIR__ . '/../../views/error.phtml');
$page
->setParam('code', $code)
;
$layout
->setParam('title', 'Error' . ' - ' . APP_NAME)
->setParam('body', $page);
});
App::get('/versions')
->desc('Get Version')
@@ -10,6 +233,7 @@ App::get('/versions')
->label('scope', 'public')
->inject('response')
->action(function (Response $response) {
$platforms = Config::getParam('platforms');
$versions = [
@@ -17,7 +241,7 @@ App::get('/versions')
];
foreach ($platforms as $platform) {
$languages = $platform['sdks'] ?? [];
$languages = $platform['languages'] ?? [];
foreach ($languages as $key => $language) {
if (isset($language['dev']) && $language['dev']) {
Binary file not shown.
+67 -93
View File
@@ -12,7 +12,6 @@ use Swoole\Runtime;
use Swoole\Timer;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Database\DateTime;
use Utopia\Logger\Log;
use Utopia\Logger\Logger;
use Utopia\Orchestration\Adapter\DockerCLI;
@@ -119,7 +118,7 @@ function logError(Throwable $error, string $action, Utopia\Route $route = null)
function getStorageDevice($root): Device
{
switch (strtolower(App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL))) {
switch (App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL)) {
case Storage::DEVICE_LOCAL:
default:
return new Local($root);
@@ -165,14 +164,14 @@ App::post('/v1/runtimes')
->desc("Create a new runtime server")
->param('runtimeId', '', new Text(64), 'Unique runtime ID.')
->param('source', '', new Text(0), 'Path to source files.')
->param('destination', '', new Text(0, 0), 'Destination folder to store build files into.', true)
->param('destination', '', new Text(0), 'Destination folder to store build files into.', true)
->param('vars', [], new Assoc(), 'Environment Variables required for the build.')
->param('commands', [], new ArrayList(new Text(1024), 100), 'Commands required to build the container. Maximum of 100 commands are allowed, each 1024 characters long.')
->param('runtime', '', new Text(128), 'Runtime for the cloud function.')
->param('baseImage', '', new Text(128), 'Base image name of the runtime.')
->param('entrypoint', '', new Text(256), 'Entrypoint of the code file.', true)
->param('remove', false, new Boolean(), 'Remove a runtime after execution.')
->param('workdir', '', new Text(256, 0), 'Working directory.', true)
->param('workdir', '', new Text(256), 'Working directory.', true)
->inject('orchestrationPool')
->inject('activeRuntimes')
->inject('response')
@@ -189,9 +188,8 @@ App::post('/v1/runtimes')
$containerId = '';
$stdout = '';
$stderr = '';
$startTime = DateTime::now();
$startTimeUnix = (new \DateTime($startTime))->getTimestamp();
$endTimeUnix = 0;
$startTime = \time();
$endTime = 0;
$orchestration = $orchestrationPool->get();
$secret = \bin2hex(\random_bytes(16));
@@ -200,8 +198,8 @@ App::post('/v1/runtimes')
$activeRuntimes->set($runtimeId, [
'id' => $containerId,
'name' => $runtimeId,
'created' => $startTimeUnix,
'updated' => $endTimeUnix,
'created' => $startTime,
'updated' => $endTime,
'status' => 'pending',
'key' => $secret,
]);
@@ -264,7 +262,7 @@ App::post('/v1/runtimes')
labels: [
'openruntimes-id' => $runtimeId,
'openruntimes-type' => 'runtime',
'openruntimes-created' => strval($startTimeUnix),
'openruntimes-created' => strval($startTime),
'openruntimes-runtime' => $runtime,
],
workdir: $workdir,
@@ -321,32 +319,28 @@ App::post('/v1/runtimes')
$stdout = 'Build Successful!';
}
$endTime = DateTime::now();
$endTimeUnix = (new \DateTime($endTime))->getTimestamp();
$duration = $endTimeUnix - $startTimeUnix;
$endTime = \time();
$container = array_merge($container, [
'status' => 'ready',
'response' => \mb_strcut($stdout, 0, 1000000), // Limit to 1MB
'stderr' => \mb_strcut($stderr, 0, 1000000), // Limit to 1MB
'startTime' => $startTime,
'endTime' => $endTime,
'duration' => $duration,
'duration' => $endTime - $startTime,
]);
if (!$remove) {
$activeRuntimes->set($runtimeId, [
'id' => $containerId,
'name' => $runtimeId,
'created' => $startTimeUnix,
'updated' => $endTimeUnix,
'status' => 'Up ' . \round($duration, 2) . 's',
'created' => $startTime,
'updated' => $endTime,
'status' => 'Up ' . \round($endTime - $startTime, 2) . 's',
'key' => $secret,
]);
}
Console::success('Build Stage completed in ' . ($duration) . ' seconds');
Console::success('Build Stage completed in ' . ($endTime - $startTime) . ' seconds');
} catch (Throwable $th) {
Console::error('Build failed: ' . $th->getMessage() . $stdout);
@@ -459,7 +453,7 @@ App::post('/v1/execution')
->desc('Create an execution')
->param('runtimeId', '', new Text(64), 'The runtimeID to execute.')
->param('vars', [], new Assoc(), 'Environment variables required for the build.')
->param('data', '', new Text(8192, 0), 'Data to be forwarded to the function, this is user specified.', true)
->param('data', '', new Text(8192), 'Data to be forwarded to the function, this is user specified.', true)
->param('timeout', 15, new Range(1, (int) App::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Function maximum execution time in seconds.')
->inject('activeRuntimes')
->inject('response')
@@ -494,7 +488,6 @@ App::post('/v1/execution')
$executionStart = \microtime(true);
$stdout = '';
$stderr = '';
$res = '';
$statusCode = 0;
$errNo = -1;
$executorResponse = '';
@@ -503,7 +496,7 @@ App::post('/v1/execution')
$ch = \curl_init();
$body = \json_encode([
'variables' => $vars,
'env' => $vars,
'payload' => $data,
'timeout' => $timeout
]);
@@ -522,7 +515,6 @@ App::post('/v1/execution')
]);
$executorResponse = \curl_exec($ch);
$executorResponse = json_decode($executorResponse, true);
$statusCode = \curl_getinfo($ch, CURLINFO_HTTP_CODE);
@@ -546,23 +538,13 @@ App::post('/v1/execution')
switch (true) {
case $statusCode >= 500:
$stderr = ($executorResponse ?? [])['stderr'] ?? 'Internal Runtime error.';
$stdout = ($executorResponse ?? [])['stdout'] ?? 'Internal Runtime error.';
$res = ($executorResponse ?? [])['response'] ?? '';
if (is_array($res)) {
$res = json_encode($res, JSON_UNESCAPED_UNICODE);
}
$stderr = $executorResponse ?? 'Internal Runtime error.';
break;
case $statusCode >= 100:
$stdout = $executorResponse['stdout'];
$res = $executorResponse['response'];
if (is_array($res)) {
$res = json_encode($res, JSON_UNESCAPED_UNICODE);
}
$stdout = $executorResponse;
break;
default:
$stderr = ($executorResponse ?? [])['stderr'] ?? 'Execution failed.';
$stdout = ($executorResponse ?? [])['stdout'] ?? '';
$stderr = $executorResponse ?? 'Execution failed.';
break;
}
@@ -575,10 +557,9 @@ App::post('/v1/execution')
$execution = [
'status' => $functionStatus,
'statusCode' => $statusCode,
'response' => \mb_strcut($res, 0, 1000000), // Limit to 1MB
'stdout' => \mb_strcut($stdout, 0, 1000000), // Limit to 1MB
'response' => \mb_strcut($stdout, 0, 1000000), // Limit to 1MB
'stderr' => \mb_strcut($stderr, 0, 1000000), // Limit to 1MB
'duration' => $executionTime,
'time' => $executionTime,
];
/** Update swoole table */
@@ -600,64 +581,57 @@ App::setResource('orchestrationPool', fn() => $orchestrationPool);
App::setResource('activeRuntimes', fn() => $activeRuntimes);
/** Set callbacks */
App::error()
->inject('utopia')
->inject('error')
->inject('request')
->inject('response')
->action(function (App $utopia, throwable $error, Request $request, Response $response) {
$route = $utopia->match($request);
logError($error, "httpError", $route);
App::error(function ($utopia, $error, $request, $response) {
$route = $utopia->match($request);
logError($error, "httpError", $route);
switch ($error->getCode()) {
case 400: // Error allowed publicly
case 401: // Error allowed publicly
case 402: // Error allowed publicly
case 403: // Error allowed publicly
case 404: // Error allowed publicly
case 406: // Error allowed publicly
case 409: // Error allowed publicly
case 412: // Error allowed publicly
case 425: // Error allowed publicly
case 429: // Error allowed publicly
case 501: // Error allowed publicly
case 503: // Error allowed publicly
$code = $error->getCode();
break;
default:
$code = 500; // All other errors get the generic 500 server error status code
}
switch ($error->getCode()) {
case 400: // Error allowed publicly
case 401: // Error allowed publicly
case 402: // Error allowed publicly
case 403: // Error allowed publicly
case 404: // Error allowed publicly
case 406: // Error allowed publicly
case 409: // Error allowed publicly
case 412: // Error allowed publicly
case 425: // Error allowed publicly
case 429: // Error allowed publicly
case 501: // Error allowed publicly
case 503: // Error allowed publicly
$code = $error->getCode();
break;
default:
$code = 500; // All other errors get the generic 500 server error status code
}
$output = [
'message' => $error->getMessage(),
'code' => $error->getCode(),
'file' => $error->getFile(),
'line' => $error->getLine(),
'trace' => $error->getTrace(),
'version' => App::getEnv('_APP_VERSION', 'UNKNOWN')
];
$output = [
'message' => $error->getMessage(),
'code' => $error->getCode(),
'file' => $error->getFile(),
'line' => $error->getLine(),
'trace' => $error->getTrace(),
'version' => App::getEnv('_APP_VERSION', 'UNKNOWN')
];
$response
->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
->addHeader('Expires', '0')
->addHeader('Pragma', 'no-cache')
->setStatusCode($code);
$response
->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
->addHeader('Expires', '0')
->addHeader('Pragma', 'no-cache')
->setStatusCode($code);
$response->json($output);
});
$response->json($output);
}, ['utopia', 'error', 'request', 'response']);
App::init()
->inject('request')
->action(function (Request $request) {
$secretKey = $request->getHeader('x-appwrite-executor-key', '');
if (empty($secretKey)) {
throw new Exception('Missing executor key', 401);
}
App::init(function ($request, $response) {
$secretKey = $request->getHeader('x-appwrite-executor-key', '');
if (empty($secretKey)) {
throw new Exception('Missing executor key', 401);
}
if ($secretKey !== App::getEnv('_APP_EXECUTOR_SECRET', '')) {
throw new Exception('Missing executor key', 401);
}
});
if ($secretKey !== App::getEnv('_APP_EXECUTOR_SECRET', '')) {
throw new Exception('Missing executor key', 401);
}
}, ['request', 'response']);
$http->on('start', function ($http) {
@@ -667,7 +641,7 @@ $http->on('start', function ($http) {
/**
* Warmup: make sure images are ready to run fast 🚀
*/
$runtimes = new Runtimes('v2');
$runtimes = new Runtimes('v1');
$allowList = empty(App::getEnv('_APP_FUNCTIONS_RUNTIMES')) ? [] : \explode(',', App::getEnv('_APP_FUNCTIONS_RUNTIMES'));
$runtimes = $runtimes->getAll(true, $allowList);
foreach ($runtimes as $runtime) {
+42 -36
View File
@@ -10,9 +10,6 @@ use Swoole\Http\Response as SwooleResponse;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Database\Validator\Authorization;
use Utopia\Audit\Audit;
use Utopia\Abuse\Adapters\TimeLimit;
@@ -38,7 +35,8 @@ $http
'http_compression_level' => 6,
'package_max_length' => $payloadSize,
'buffer_output_size' => $payloadSize,
]);
])
;
$http->on('WorkerStart', function ($server, $workerId) {
Console::success('Worker ' . ++$workerId . ' started successfully');
@@ -52,7 +50,7 @@ $http->on('AfterReload', function ($server, $workerId) {
Console::success('Reload completed...');
});
Files::load(__DIR__ . '/../console');
Files::load(__DIR__ . '/../public');
include __DIR__ . '/controllers/general.php';
@@ -80,21 +78,26 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
}
} while ($attempts < $max);
App::setResource('db', fn () => $db);
App::setResource('cache', fn () => $redis);
App::setResource('db', fn() => $db);
App::setResource('cache', fn() => $redis);
/** @var Utopia\Database\Database $dbForConsole */
$dbForConsole = $app->getResource('dbForConsole');
$dbForConsole = $app->getResource('dbForConsole'); /** @var Utopia\Database\Database $dbForConsole */
Console::success('[Setup] - Server database init started...');
$collections = Config::getParam('collections', []); /** @var array $collections */
/** @var array $collections */
$collections = Config::getParam('collections', []);
if (!$dbForConsole->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'))) {
$redis->flushAll();
Console::success('[Setup] - Creating database: appwrite...');
$dbForConsole->create(App::getEnv('_APP_DB_SCHEMA', 'appwrite'));
}
try {
Console::success('[Setup] - Creating database: appwrite...');
$dbForConsole->create();
} catch (\Exception $e) {
Console::success('[Setup] - Creating metadata table: appwrite...');
$dbForConsole->createMetadata();
} catch (\Throwable $th) {
Console::success('[Setup] - Skip: metadata table already exists');
}
@@ -116,9 +119,9 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
continue;
}
/**
* Skip to prevent 0.16 migration issues.
* Skip to prevent 0.15 migration issues.
*/
if (in_array($key, ['cache', 'variables']) && $dbForConsole->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), 'bucket_1')) {
if ($key === 'databases' && $dbForConsole->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), 'collections')) {
continue;
}
@@ -129,7 +132,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
foreach ($collection['attributes'] as $attribute) {
$attributes[] = new Document([
'$id' => ID::custom($attribute['$id']),
'$id' => $attribute['$id'],
'type' => $attribute['type'],
'size' => $attribute['size'],
'required' => $attribute['required'],
@@ -143,7 +146,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
foreach ($collection['indexes'] as $index) {
$indexes[] = new Document([
'$id' => ID::custom($index['$id']),
'$id' => $index['$id'],
'type' => $index['type'],
'attributes' => $index['attributes'],
'lengths' => $index['lengths'],
@@ -154,25 +157,20 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
$dbForConsole->createCollection($key, $attributes, $indexes);
}
if ($dbForConsole->getDocument('buckets', 'default')->isEmpty() && !$dbForConsole->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), 'bucket_1')) {
if ($dbForConsole->getDocument('buckets', 'default')->isEmpty()) {
Console::success('[Setup] - Creating default bucket...');
$dbForConsole->createDocument('buckets', new Document([
'$id' => ID::custom('default'),
'$collection' => ID::custom('buckets'),
'$id' => 'default',
'$collection' => 'buckets',
'name' => 'Default',
'permission' => 'file',
'maximumFileSize' => (int) App::getEnv('_APP_STORAGE_LIMIT', 0), // 10MB
'allowedFileExtensions' => [],
'enabled' => true,
'compression' => 'gzip',
'encryption' => true,
'antivirus' => true,
'fileSecurity' => true,
'$permissions' => [
Permission::create(Role::any()),
Permission::read(Role::any()),
Permission::update(Role::any()),
Permission::delete(Role::any()),
],
'$read' => ['role:all'],
'$write' => ['role:all'],
'search' => 'buckets Default',
]));
@@ -189,7 +187,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
foreach ($files['attributes'] as $attribute) {
$attributes[] = new Document([
'$id' => ID::custom($attribute['$id']),
'$id' => $attribute['$id'],
'type' => $attribute['type'],
'size' => $attribute['size'],
'required' => $attribute['required'],
@@ -203,7 +201,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) {
foreach ($files['indexes'] as $index) {
$indexes[] = new Document([
'$id' => ID::custom($index['$id']),
'$id' => $index['$id'],
'type' => $index['type'],
'attributes' => $index['attributes'],
'lengths' => $index['lengths'],
@@ -238,7 +236,8 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo
->setContentType(Files::getFileMimeType($request->getURI()))
->addHeader('Cache-Control', 'public, max-age=' . $time)
->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time) . ' GMT') // 45 days cache
->send(Files::getFileContents($request->getURI()));
->send(Files::getFileContents($request->getURI()))
;
return;
}
@@ -248,12 +247,12 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo
$db = $register->get('dbPool')->get();
$redis = $register->get('redisPool')->get();
App::setResource('db', fn () => $db);
App::setResource('cache', fn () => $redis);
App::setResource('db', fn() => $db);
App::setResource('cache', fn() => $redis);
try {
Authorization::cleanRoles();
Authorization::setRole(Role::any()->toString());
Authorization::setRole('role:all');
$app->run($request, $response);
} catch (\Throwable $th) {
@@ -295,7 +294,7 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo
$log->addExtra('line', $th->getLine());
$log->addExtra('trace', $th->getTraceAsString());
$log->addExtra('detailedTrace', $th->getTrace());
$log->addExtra('roles', Authorization::getRoles());
$log->addExtra('roles', Authorization::$roles);
$action = $route->getLabel("sdk.namespace", "UNKNOWN_NAMESPACE") . '.' . $route->getLabel("sdk.method", "UNKNOWN_METHOD");
$log->setAction($action);
@@ -316,6 +315,13 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo
Console::error('[Error] File: ' . $th->getFile());
Console::error('[Error] Line: ' . $th->getLine());
/**
* Reset Database connection if PDOException was thrown.
*/
if ($th instanceof PDOException) {
$db = null;
}
$swooleResponse->setStatusCode(500);
$output = ((App::isDevelopment())) ? [
+80 -263
View File
@@ -18,9 +18,17 @@ ini_set('display_startup_errors', 1);
ini_set('default_socket_timeout', -1);
error_reporting(E_ALL);
use Appwrite\Extend\PDO;
use Ahc\Jwt\JWT;
use Ahc\Jwt\JWTException;
use Appwrite\Extend\Exception;
use Appwrite\Auth\Auth;
use Appwrite\Auth\Phone\Mock;
use Appwrite\Auth\Phone\Telesign;
use Appwrite\Auth\Phone\TextMagic;
use Appwrite\Auth\Phone\Twilio;
use Appwrite\Auth\Phone\Msg91;
use Appwrite\Auth\Phone\Vonage;
use Appwrite\DSN\DSN;
use Appwrite\Event\Audit;
use Appwrite\Event\Database as EventDatabase;
@@ -28,53 +36,41 @@ use Appwrite\Event\Delete;
use Appwrite\Event\Event;
use Appwrite\Event\Mail;
use Appwrite\Event\Phone;
use Appwrite\Extend\Exception;
use Appwrite\Extend\PDO;
use Appwrite\GraphQL\Promises\Adapter\Swoole;
use Appwrite\GraphQL\Schema;
use Appwrite\Network\Validator\Email;
use Appwrite\Network\Validator\Origin;
use Appwrite\Network\Validator\IP;
use Appwrite\Network\Validator\URL;
use Appwrite\OpenSSL\OpenSSL;
use Appwrite\Usage\Stats;
use Appwrite\Stats\Stats;
use Appwrite\Utopia\View;
use Utopia\App;
use Utopia\Logger\Logger;
use Utopia\Config\Config;
use Utopia\Locale\Locale;
use Utopia\Registry\Registry;
use MaxMind\Db\Reader;
use PHPMailer\PHPMailer\PHPMailer;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Cache\Cache;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Document;
use Utopia\Database\Database;
use Utopia\Database\Validator\Structure;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\Range;
use Utopia\Validator\WhiteList;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Database\RedisConfig;
use Swoole\Database\RedisPool;
use Utopia\App;
use Utopia\Database\Helpers\ID;
use Utopia\Logger\Logger;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Cache\Cache;
use Utopia\Config\Config;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\Datetime as DatetimeValidator;
use Utopia\Database\Validator\Structure;
use Utopia\Locale\Locale;
use Utopia\Messaging\Adapters\SMS\Mock;
use Utopia\Messaging\Adapters\SMS\Msg91;
use Utopia\Messaging\Adapters\SMS\Telesign;
use Utopia\Messaging\Adapters\SMS\TextMagic;
use Utopia\Messaging\Adapters\SMS\Twilio;
use Utopia\Messaging\Adapters\SMS\Vonage;
use Utopia\Registry\Registry;
use Utopia\Storage\Device;
use Utopia\Storage\Storage;
use Utopia\Storage\Device\Backblaze;
use Utopia\Storage\Device\DOSpaces;
use Utopia\Storage\Device\Linode;
use Utopia\Storage\Device\Local;
use Utopia\Storage\Device\S3;
use Utopia\Storage\Device\Linode;
use Utopia\Storage\Device\Wasabi;
use Utopia\Storage\Storage;
use Utopia\Validator\Range;
use Utopia\Validator\IP;
use Utopia\Validator\URL;
use Utopia\Validator\WhiteList;
const APP_NAME = 'Appwrite';
const APP_DOMAIN = 'appwrite.io';
@@ -86,26 +82,17 @@ const APP_MODE_ADMIN = 'admin';
const APP_PAGING_LIMIT = 12;
const APP_LIMIT_COUNT = 5000;
const APP_LIMIT_USERS = 10000;
const APP_LIMIT_USER_PASSWORD_HISTORY = 20;
const APP_LIMIT_USER_SESSIONS_MAX = 100;
const APP_LIMIT_USER_SESSIONS_DEFAULT = 10;
const APP_LIMIT_ANTIVIRUS = 20000000; //20MB
const APP_LIMIT_ENCRYPTION = 20000000; //20MB
const APP_LIMIT_COMPRESSION = 20000000; //20MB
const APP_LIMIT_ARRAY_PARAMS_SIZE = 100; // Default maximum of how many elements can there be in API parameter that expects array value
const APP_LIMIT_ARRAY_ELEMENT_SIZE = 4096; // Default maximum length of element in array parameter represented by maximum URL length.
const APP_LIMIT_SUBQUERY = 1000;
const APP_LIMIT_WRITE_RATE_DEFAULT = 60; // Default maximum write rate per rate period
const APP_LIMIT_WRITE_RATE_PERIOD_DEFAULT = 60; // Default maximum write rate period in seconds
const APP_LIMIT_LIST_DEFAULT = 25; // Default maximum number of items to return in list API calls
const APP_KEY_ACCCESS = 24 * 60 * 60; // 24 hours
const APP_CACHE_UPDATE = 24 * 60 * 60; // 24 hours
const APP_CACHE_BUSTER = 503;
const APP_VERSION_STABLE = '1.3.1';
const APP_CACHE_BUSTER = 402;
const APP_VERSION_STABLE = '0.15.2';
const APP_DATABASE_ATTRIBUTE_EMAIL = 'email';
const APP_DATABASE_ATTRIBUTE_ENUM = 'enum';
const APP_DATABASE_ATTRIBUTE_IP = 'ip';
const APP_DATABASE_ATTRIBUTE_DATETIME = 'datetime';
const APP_DATABASE_ATTRIBUTE_URL = 'url';
const APP_DATABASE_ATTRIBUTE_INT_RANGE = 'intRange';
const APP_DATABASE_ATTRIBUTE_FLOAT_RANGE = 'floatRange';
@@ -156,12 +143,6 @@ const DELETE_TYPE_USAGE = 'usage';
const DELETE_TYPE_REALTIME = 'realtime';
const DELETE_TYPE_BUCKETS = 'buckets';
const DELETE_TYPE_SESSIONS = 'sessions';
const DELETE_TYPE_CACHE_BY_TIMESTAMP = 'cacheByTimeStamp';
const DELETE_TYPE_CACHE_BY_RESOURCE = 'cacheByResource';
// Compression type
const COMPRESSION_TYPE_NONE = 'none';
const COMPRESSION_TYPE_GZIP = 'gzip';
const COMPRESSION_TYPE_ZSTD = 'zstd';
// Mail Types
const MAIL_TYPE_VERIFICATION = 'verification';
const MAIL_TYPE_MAGIC_SESSION = 'magicSession';
@@ -194,7 +175,6 @@ Config::load('roles', __DIR__ . '/config/roles.php'); // User roles and scopes
Config::load('scopes', __DIR__ . '/config/scopes.php'); // User roles and scopes
Config::load('services', __DIR__ . '/config/services.php'); // List of services
Config::load('variables', __DIR__ . '/config/variables.php'); // List of env variables
Config::load('regions', __DIR__ . '/config/regions.php'); // List of available regions
Config::load('avatar-browsers', __DIR__ . '/config/avatars/browsers.php');
Config::load('avatar-credit-cards', __DIR__ . '/config/avatars/credit-cards.php');
Config::load('avatar-flags', __DIR__ . '/config/avatars/flags.php');
@@ -285,23 +265,11 @@ Database::addFilter(
return null;
},
function (mixed $value, Document $document, Database $database) {
$attributes = $database->find('attributes', [
Query::equal('collectionInternalId', [$document->getInternalId()]),
Query::equal('databaseInternalId', [$document->getAttribute('databaseInternalId')]),
Query::limit($database->getLimitForAttributes()),
]);
foreach ($attributes as $attribute) {
if ($attribute->getAttribute('type') === Database::VAR_RELATIONSHIP) {
$options = $attribute->getAttribute('options');
foreach ($options as $key => $value) {
$attribute->setAttribute($key, $value);
}
$attribute->removeAttribute('options');
}
}
return $attributes;
return $database
->find('attributes', [
new Query('collectionInternalId', Query::TYPE_EQUAL, [$document->getInternalId()]),
new Query('databaseInternalId', Query::TYPE_EQUAL, [$document->getAttribute('databaseInternalId')])
], $database->getAttributeLimit(), 0, []);
}
);
@@ -313,10 +281,9 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return $database
->find('indexes', [
Query::equal('collectionInternalId', [$document->getInternalId()]),
Query::equal('databaseInternalId', [$document->getAttribute('databaseInternalId')]),
Query::limit(64),
]);
new Query('collectionInternalId', Query::TYPE_EQUAL, [$document->getInternalId()]),
new Query('databaseInternalId', Query::TYPE_EQUAL, [$document->getAttribute('databaseInternalId')])
], 64);
}
);
@@ -328,9 +295,8 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return $database
->find('platforms', [
Query::equal('projectInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]);
new Query('projectInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY);
}
);
@@ -342,9 +308,8 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return $database
->find('domains', [
Query::equal('projectInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]);
new Query('projectInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY);
}
);
@@ -356,9 +321,8 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return $database
->find('keys', [
Query::equal('projectInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]);
new Query('projectInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY);
}
);
@@ -370,9 +334,8 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return $database
->find('webhooks', [
Query::equal('projectInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]);
new Query('projectInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY);
}
);
@@ -383,9 +346,8 @@ Database::addFilter(
},
function (mixed $value, Document $document, Database $database) {
return Authorization::skip(fn () => $database->find('sessions', [
Query::equal('userInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]));
new Query('userInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY));
}
);
@@ -397,9 +359,8 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return Authorization::skip(fn() => $database
->find('tokens', [
Query::equal('userInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]));
new Query('userInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY));
}
);
@@ -411,23 +372,8 @@ Database::addFilter(
function (mixed $value, Document $document, Database $database) {
return Authorization::skip(fn() => $database
->find('memberships', [
Query::equal('userInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]));
}
);
Database::addFilter(
'subQueryVariables',
function (mixed $value) {
return null;
},
function (mixed $value, Document $document, Database $database) {
return $database
->find('variables', [
Query::equal('functionInternalId', [$document->getInternalId()]),
Query::limit(APP_LIMIT_SUBQUERY),
]);
new Query('userInternalId', Query::TYPE_EQUAL, [$document->getInternalId()])
], APP_LIMIT_SUBQUERY));
}
);
@@ -464,10 +410,6 @@ Structure::addFormat(APP_DATABASE_ATTRIBUTE_EMAIL, function () {
return new Email();
}, Database::VAR_STRING);
Structure::addFormat(APP_DATABASE_ATTRIBUTE_DATETIME, function () {
return new DatetimeValidator();
}, Database::VAR_DATETIME);
Structure::addFormat(APP_DATABASE_ATTRIBUTE_ENUM, function ($attribute) {
$elements = $attribute['formatOptions']['elements'];
return new WhiteList($elements, true);
@@ -506,7 +448,7 @@ $register->set('logger', function () {
}
if (!Logger::hasProvider($providerName)) {
throw new Exception(Exception::GENERAL_SERVER_ERROR, "Logging provider not supported. Logging is disabled");
throw new Exception("Logging provider not supported. Logging disabled.", 500, Exception::GENERAL_SERVER_ERROR);
}
$classname = '\\Utopia\\Logger\\Adapter\\' . \ucfirst($providerName);
@@ -617,13 +559,7 @@ $register->set('smtp', function () {
return $mail;
});
$register->set('geodb', function () {
return new Reader(__DIR__ . '/assets/dbip/dbip-country-lite-2023-01.mmdb');
});
$register->set('passwordsDictionary', function () {
$content = \file_get_contents(__DIR__ . '/assets/security/10k-common-passwords');
$content = explode("\n", $content);
$content = array_flip($content);
return $content;
return new Reader(__DIR__ . '/db/DBIP/dbip-country-lite-2022-06.mmdb');
});
$register->set('db', function () {
// This is usually for our workers or CLI commands scope
@@ -652,9 +588,6 @@ $register->set('cache', function () {
return $redis;
});
$register->set('promiseAdapter', function () {
return new Swoole();
});
/*
* Localization
@@ -756,6 +689,13 @@ App::setResource('loggerBreadcrumbs', function () {
App::setResource('register', fn() => $register);
App::setResource('layout', function ($locale) {
$layout = new View(__DIR__ . '/views/layouts/default.phtml');
$layout->setParam('locale', $locale);
return $layout;
}, ['locale']);
App::setResource('locale', fn() => new Locale(App::getEnv('_APP_LOCALE', 'en')));
// Queues
@@ -771,9 +711,9 @@ App::setResource('usage', function ($register) {
App::setResource('clients', function ($request, $console, $project) {
$console->setAttribute('platforms', [ // Always allow current host
'$collection' => ID::custom('platforms'),
'$collection' => 'platforms',
'name' => 'Current Host',
'type' => Origin::CLIENT_TYPE_WEB,
'type' => 'web',
'hostname' => $request->getHostname(),
], Document::SET_TYPE_APPEND);
@@ -785,7 +725,7 @@ App::setResource('clients', function ($request, $console, $project) {
fn ($node) => $node['hostname'],
\array_filter(
$console->getAttribute('platforms', []),
fn ($node) => (isset($node['type']) && ($node['type'] === Origin::CLIENT_TYPE_WEB) && isset($node['hostname']) && !empty($node['hostname']))
fn ($node) => (isset($node['type']) && $node['type'] === 'web' && isset($node['hostname']) && !empty($node['hostname']))
)
);
@@ -796,7 +736,7 @@ App::setResource('clients', function ($request, $console, $project) {
fn ($node) => $node['hostname'],
\array_filter(
$project->getAttribute('platforms', []),
fn ($node) => (isset($node['type']) && ($node['type'] === Origin::CLIENT_TYPE_WEB || $node['type'] === Origin::CLIENT_TYPE_FLUTTER_WEB) && isset($node['hostname']) && !empty($node['hostname']))
fn ($node) => (isset($node['type']) && $node['type'] === 'web' && isset($node['hostname']) && !empty($node['hostname']))
)
)
)
@@ -816,11 +756,9 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
Authorization::setDefaultStatus(true);
Auth::setCookieName('a_session_' . $project->getId());
$authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;
if (APP_MODE_ADMIN === $mode) {
Auth::setCookieName('a_session_' . $console->getId());
$authDuration = Auth::TOKEN_EXPIRATION_LOGIN_LONG;
}
$session = Auth::decodeSession(
@@ -849,7 +787,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
if (APP_MODE_ADMIN !== $mode) {
if ($project->isEmpty()) {
$user = new Document(['$id' => ID::custom(''), '$collection' => 'users']);
$user = new Document(['$id' => '', '$collection' => 'users']);
} else {
$user = $dbForProject->getDocument('users', Auth::$unique);
}
@@ -859,16 +797,16 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
if (
$user->isEmpty() // Check a document has been found in the DB
|| !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration)
|| !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret)
) { // Validate user has valid login token
$user = new Document(['$id' => ID::custom(''), '$collection' => 'users']);
$user = new Document(['$id' => '', '$collection' => 'users']);
}
if (APP_MODE_ADMIN === $mode) {
if ($user->find('teamId', $project->getAttribute('teamId'), 'memberships')) {
Authorization::setDefaultStatus(false); // Cancel security segmentation for admin users.
} else {
$user = new Document(['$id' => ID::custom(''), '$collection' => 'users']);
$user = new Document(['$id' => '', '$collection' => 'users']);
}
}
@@ -880,7 +818,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
try {
$payload = $jwt->decode($authJWT);
} catch (JWTException $error) {
throw new Exception(Exception::USER_JWT_INVALID, 'Failed to verify JWT. ' . $error->getMessage());
throw new Exception('Failed to verify JWT. ' . $error->getMessage(), 401, Exception::USER_JWT_INVALID);
}
$jwtUserId = $payload['userId'] ?? '';
@@ -891,7 +829,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons
}
if (empty($user->find('$id', $jwtSessionId, 'sessions'))) { // Match JWT to active token
$user = new Document(['$id' => ID::custom(''), '$collection' => 'users']);
$user = new Document(['$id' => '', '$collection' => 'users']);
}
}
@@ -916,10 +854,10 @@ App::setResource('project', function ($dbForConsole, $request, $console) {
App::setResource('console', function () {
return new Document([
'$id' => ID::custom('console'),
'$internalId' => ID::custom('console'),
'$id' => 'console',
'$internalId' => 'console',
'name' => 'Appwrite',
'$collection' => ID::custom('projects'),
'$collection' => 'projects',
'description' => 'Appwrite core engine',
'logo' => '',
'teamId' => -1,
@@ -927,9 +865,9 @@ App::setResource('console', function () {
'keys' => [],
'platforms' => [
[
'$collection' => ID::custom('platforms'),
'$collection' => 'platforms',
'name' => 'Localhost',
'type' => Origin::CLIENT_TYPE_WEB,
'type' => 'web',
'hostname' => 'localhost',
], // Current host is added on app init
],
@@ -941,7 +879,6 @@ App::setResource('console', function () {
'legalTaxId' => '',
'auths' => [
'limit' => (App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled') === 'enabled') ? 1 : 0, // limit signup to 1 user
'duration' => Auth::TOKEN_EXPIRATION_LOGIN_LONG, // 1 Year in seconds
],
'authWhitelistEmails' => (!empty(App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [],
'authWhitelistIPs' => (!empty(App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null)) : [],
@@ -987,7 +924,7 @@ App::setResource('deviceBuilds', function ($project) {
function getDevice($root): Device
{
switch (strtolower(App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL))) {
switch (App::getEnv('_APP_STORAGE_DEVICE', Storage::DEVICE_LOCAL)) {
case Storage::DEVICE_LOCAL:
default:
return new Local($root);
@@ -1045,18 +982,13 @@ App::setResource('geodb', function ($register) {
return $register->get('geodb');
}, ['register']);
App::setResource('passwordsDictionary', function ($register) {
/** @var Utopia\Registry\Registry $register */
return $register->get('passwordsDictionary');
}, ['register']);
App::setResource('sms', function () {
$dsn = new DSN(App::getEnv('_APP_SMS_PROVIDER'));
App::setResource('phone', function () {
$dsn = new DSN(App::getEnv('_APP_PHONE_PROVIDER'));
$user = $dsn->getUser();
$secret = $dsn->getPassword();
return match ($dsn->getHost()) {
'mock' => new Mock($user, $secret), // used for tests
'mock' => new Mock('', ''), // used for tests
'twilio' => new Twilio($user, $secret),
'text-magic' => new TextMagic($user, $secret),
'telesign' => new Telesign($user, $secret),
@@ -1065,118 +997,3 @@ App::setResource('sms', function () {
default => null
};
});
App::setResource('servers', function () {
$platforms = Config::getParam('platforms');
$server = $platforms[APP_PLATFORM_SERVER];
$languages = array_map(function ($language) {
return strtolower($language['name']);
}, $server['sdks']);
return $languages;
});
App::setResource('promiseAdapter', function ($register) {
return $register->get('promiseAdapter');
}, ['register']);
App::setResource('schema', function ($utopia, $dbForProject) {
$complexity = function (int $complexity, array $args) {
$queries = Query::parseQueries($args['queries'] ?? []);
$query = Query::getByType($queries, Query::TYPE_LIMIT)[0] ?? null;
$limit = $query ? $query->getValue() : APP_LIMIT_LIST_DEFAULT;
return $complexity * $limit;
};
$attributes = function (int $limit, int $offset) use ($dbForProject) {
$attrs = Authorization::skip(fn() => $dbForProject->find('attributes', [
Query::limit($limit),
Query::offset($offset),
]));
return \array_map(function ($attr) {
return $attr->getArrayCopy();
}, $attrs);
};
$urls = [
'list' => function (string $databaseId, string $collectionId, array $args) {
return "/v1/databases/$databaseId/collections/$collectionId/documents";
},
'create' => function (string $databaseId, string $collectionId, array $args) {
return "/v1/databases/$databaseId/collections/$collectionId/documents";
},
'read' => function (string $databaseId, string $collectionId, array $args) {
return "/v1/databases/$databaseId/collections/$collectionId/documents/{$args['documentId']}";
},
'update' => function (string $databaseId, string $collectionId, array $args) {
return "/v1/databases/$databaseId/collections/$collectionId/documents/{$args['documentId']}";
},
'delete' => function (string $databaseId, string $collectionId, array $args) {
return "/v1/databases/$databaseId/collections/$collectionId/documents/{$args['documentId']}";
},
];
$params = [
'list' => function (string $databaseId, string $collectionId, array $args) {
return [ 'queries' => $args['queries']];
},
'create' => function (string $databaseId, string $collectionId, array $args) {
$id = $args['id'] ?? 'unique()';
$permissions = $args['permissions'] ?? null;
unset($args['id']);
unset($args['permissions']);
// Order must be the same as the route params
return [
'databaseId' => $databaseId,
'documentId' => $id,
'collectionId' => $collectionId,
'data' => $args,
'permissions' => $permissions,
];
},
'update' => function (string $databaseId, string $collectionId, array $args) {
$documentId = $args['id'];
$permissions = $args['permissions'] ?? null;
unset($args['id']);
unset($args['permissions']);
// Order must be the same as the route params
return [
'databaseId' => $databaseId,
'collectionId' => $collectionId,
'documentId' => $documentId,
'data' => $args,
'permissions' => $permissions,
];
},
];
return Schema::build(
$utopia,
$complexity,
$attributes,
$urls,
$params,
);
}, ['utopia', 'dbForProject']);
App::setResource('requestTimestamp', function ($request) {
//TODO: Move this to the Request class itself
$timestampHeader = $request->getHeader('x-appwrite-timestamp');
$requestTimestamp = null;
if (!empty($timestampHeader)) {
try {
$requestTimestamp = new \DateTime($timestampHeader);
} catch (\Throwable $e) {
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid X-Appwrite-Timestamp header value');
}
}
return $requestTimestamp;
}, ['request']);
-1
View File
@@ -35,7 +35,6 @@ foreach (
realpath(__DIR__ . '/../vendor/symfony'),
realpath(__DIR__ . '/../vendor/mongodb'),
realpath(__DIR__ . '/../vendor/utopia-php/websocket'), // TODO: remove workerman autoload
realpath(__DIR__ . '/../vendor/utopia-php/cache'), // TODO: remove memcache autoload
] as $key => $value
) {
if ($value !== false) {
+24 -23
View File
@@ -1,6 +1,7 @@
<?php
use Appwrite\Auth\Auth;
use Appwrite\Event\Event;
use Appwrite\Messaging\Adapter\Realtime;
use Appwrite\Network\Validator\Origin;
use Appwrite\Utopia\Response;
@@ -13,11 +14,8 @@ use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\App;
use Utopia\CLI\Console;
use Utopia\Database\Helpers\ID;
use Utopia\Database\Helpers\Role;
use Utopia\Logger\Log;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Cache\Cache;
use Utopia\Database\Adapter\MariaDB;
@@ -136,7 +134,7 @@ function getDatabase(Registry &$register, string $namespace)
$server->onStart(function () use ($stats, $register, $containerId, &$statsDocument, $logError) {
sleep(5); // wait for the initial database schema to be ready
Console::success('Server started successfully');
Console::success('Server started succefully');
/**
* Create document for this worker to share stats across Containers.
@@ -148,11 +146,12 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume
try {
$attempts++;
$document = new Document([
'$id' => ID::unique(),
'$collection' => ID::custom('realtime'),
'$permissions' => [],
'$id' => $database->getId(),
'$collection' => 'realtime',
'$read' => [],
'$write' => [],
'container' => $containerId,
'timestamp' => DateTime::now(),
'timestamp' => time(),
'value' => '{}'
]);
@@ -182,7 +181,7 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume
[$database, $returnDatabase] = getDatabase($register, '_console');
$statsDocument
->setAttribute('timestamp', DateTime::now())
->setAttribute('timestamp', time())
->setAttribute('value', json_encode($payload));
Authorization::skip(fn () => $database->updateDocument('realtime', $statsDocument->getId(), $statsDocument));
@@ -204,13 +203,13 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
/**
* Sending current connections to project channels on the console project every 5 seconds.
*/
if ($realtime->hasSubscriber('console', Role::users()->toString(), 'project')) {
if ($realtime->hasSubscriber('console', 'role:member', 'project')) {
[$database, $returnDatabase] = getDatabase($register, '_console');
$payload = [];
$list = Authorization::skip(fn () => $database->find('realtime', [
Query::greaterThan('timestamp', DateTime::addSeconds(new \DateTime(), -15)),
new Query('timestamp', Query::TYPE_GREATER, [(time() - 15)])
]));
/**
@@ -237,7 +236,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
'data' => [
'events' => ['stats.connections'],
'channels' => ['project'],
'timestamp' => DateTime::formatTz(DateTime::now()),
'timestamp' => time(),
'payload' => [
$projectId => $payload[$projectId]
]
@@ -255,16 +254,16 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
/**
* Sending test message for SDK E2E tests every 5 seconds.
*/
if ($realtime->hasSubscriber('console', Role::guests()->toString(), 'tests')) {
if ($realtime->hasSubscriber('console', 'role:guest', 'tests')) {
$payload = ['response' => 'WS:/v1/realtime:passed'];
$event = [
'project' => 'console',
'roles' => [Role::guests()->toString()],
'roles' => ['role:guest'],
'data' => [
'events' => ['test.event'],
'channels' => ['tests'],
'timestamp' => DateTime::formatTz(DateTime::now()),
'timestamp' => time(),
'payload' => $payload
]
];
@@ -306,7 +305,7 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats,
if ($realtime->hasSubscriber($projectId, 'user:' . $userId)) {
$connection = array_key_first(reset($realtime->subscriptions[$projectId]['user:' . $userId]));
[$consoleDatabase, $returnConsoleDatabase] = getDatabase($register, '_console');
$project = Authorization::skip(fn () => $consoleDatabase->getDocument('projects', $projectId));
$project = Authorization::skip(fn() => $consoleDatabase->getDocument('projects', $projectId));
[$database, $returnDatabase] = getDatabase($register, "_{$project->getInternalId()}");
$user = $database->getDocument('users', $userId);
@@ -434,7 +433,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
$realtime->subscribe($project->getId(), $connection, $roles, $channels);
$user = empty($user->getId()) ? null : $response->output($user, Response::MODEL_ACCOUNT);
$user = empty($user->getId()) ? null : $response->output($user, Response::MODEL_USER);
$server->send([$connection], json_encode([
'type' => 'connected',
@@ -484,7 +483,6 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server,
$server->onMessage(function (int $connection, string $message) use ($server, $register, $realtime, $containerId) {
try {
$app = new App('UTC');
$response = new Response(new SwooleResponse());
$db = $register->get('dbPool')->get();
$redis = $register->get('redisPool')->get();
@@ -494,8 +492,12 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re
$database->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite'));
$database->setNamespace("_console");
$projectId = $realtime->connections[$connection]['projectId'];
$project = $projectId === 'console' ? $app->getResource('console') : Authorization::skip(fn () => $database->getDocument('projects', $projectId));
$database->setNamespace("_{$project->getInternalId()}");
if ($projectId !== 'console') {
$project = Authorization::skip(fn() => $database->getDocument('projects', $projectId));
$database->setNamespace("_{$project->getInternalId()}");
}
/*
* Abuse Check
*
@@ -533,11 +535,10 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re
Auth::$secret = $session['secret'] ?? '';
$user = $database->getDocument('users', Auth::$unique);
$authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;
if (
empty($user->getId()) // Check a document has been found in the DB
|| !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration) // Validate user has valid login token
|| !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret) // Validate user has valid login token
) {
// cookie not valid
throw new Exception('Session is not valid.', 1003);
@@ -547,7 +548,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re
$channels = Realtime::convertChannels(array_flip($realtime->connections[$connection]['channels']), $user->getId());
$realtime->subscribe($realtime->connections[$connection]['projectId'], $connection, $roles, $channels);
$user = $response->output($user, Response::MODEL_ACCOUNT);
$user = $response->output($user, Response::MODEL_USER);
$server->send([$connection], json_encode([
'type' => 'response',
'data' => [
+17 -30
View File
@@ -11,7 +11,6 @@ use Utopia\Cache\Cache;
use Utopia\CLI\Console;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Database\Document;
use Utopia\Database\Query;
@@ -58,7 +57,7 @@ $cli
{
(new Delete())
->setType(DELETE_TYPE_EXECUTIONS)
->setDatetime(DateTime::addSeconds(new \DateTime(), -1 * $interval))
->setTimestamp(time() - $interval)
->trigger();
}
@@ -66,7 +65,7 @@ $cli
{
(new Delete())
->setType(DELETE_TYPE_ABUSE)
->setDatetime(DateTime::addSeconds(new \DateTime(), -1 * $interval))
->setTimestamp(time() - $interval)
->trigger();
}
@@ -74,15 +73,16 @@ $cli
{
(new Delete())
->setType(DELETE_TYPE_AUDIT)
->setDatetime(DateTime::addSeconds(new \DateTime(), -1 * $interval))
->setTimestamp(time() - $interval)
->trigger();
}
function notifyDeleteUsageStats(int $usageStatsRetentionHourly)
function notifyDeleteUsageStats(int $interval30m, int $interval1d)
{
(new Delete())
->setType(DELETE_TYPE_USAGE)
->setUsageRetentionHourlyDateTime(DateTime::addSeconds(new \DateTime(), -1 * $usageStatsRetentionHourly))
->setTimestamp1d(time() - $interval1d)
->setTimestamp30m(time() - $interval30m)
->trigger();
}
@@ -90,7 +90,7 @@ $cli
{
(new Delete())
->setType(DELETE_TYPE_REALTIME)
->setDatetime(DateTime::addSeconds(new \DateTime(), -60))
->setTimestamp(time() - 60)
->trigger();
}
@@ -98,18 +98,17 @@ $cli
{
(new Delete())
->setType(DELETE_TYPE_SESSIONS)
->setTimestamp(time() - Auth::TOKEN_EXPIRATION_LOGIN_LONG)
->trigger();
}
function renewCertificates($dbForConsole)
{
$time = DateTime::now();
$time = date('d-m-Y H:i:s', time());
$certificates = $dbForConsole->find('certificates', [
Query::lessThan('attempts', 5), // Maximum 5 attempts
Query::lessThanEqual('renewDate', $time), // includes 60 days cooldown (we have 30 days to renew)
Query::limit(200), // Limit 200 comes from LetsEncrypt (300 orders per 3 hours, keeping some for new domains)
]);
new Query('attempts', Query::TYPE_LESSEREQUAL, [5]), // Maximum 5 attempts
new Query('renewDate', Query::TYPE_LESSEREQUAL, [\time()]) // includes 60 days cooldown (we have 30 days to renew)
], 200); // Limit 200 comes from LetsEncrypt (300 orders per 3 hours, keeping some for new domains)
if (\count($certificates) > 0) {
@@ -128,37 +127,25 @@ $cli
}
}
function notifyDeleteCache($interval)
{
(new Delete())
->setType(DELETE_TYPE_CACHE_BY_TIMESTAMP)
->setDatetime(DateTime::addSeconds(new \DateTime(), -1 * $interval))
->trigger();
}
// # of days in seconds (1 day = 86400s)
$interval = (int) App::getEnv('_APP_MAINTENANCE_INTERVAL', '86400');
$executionLogsRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_EXECUTION', '1209600');
$auditLogRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_AUDIT', '1209600');
$abuseLogsRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_ABUSE', '86400');
$usageStatsRetentionHourly = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_USAGE_HOURLY', '8640000'); //100 days
$usageStatsRetention30m = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_USAGE_30M', '129600'); //36 hours
$usageStatsRetention1d = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_USAGE_1D', '8640000'); // 100 days
$cacheRetention = (int) App::getEnv('_APP_MAINTENANCE_RETENTION_CACHE', '2592000'); // 30 days
Console::loop(function () use ($interval, $executionLogsRetention, $abuseLogsRetention, $auditLogRetention, $usageStatsRetentionHourly, $cacheRetention) {
Console::loop(function () use ($interval, $executionLogsRetention, $abuseLogsRetention, $auditLogRetention, $usageStatsRetention30m, $usageStatsRetention1d) {
$database = getConsoleDB();
$time = DateTime::now();
$time = date('d-m-Y H:i:s', time());
Console::info("[{$time}] Notifying workers with maintenance tasks every {$interval} seconds");
notifyDeleteExecutionLogs($executionLogsRetention);
notifyDeleteAbuseLogs($abuseLogsRetention);
notifyDeleteAuditLogs($auditLogRetention);
notifyDeleteUsageStats($usageStatsRetentionHourly);
notifyDeleteUsageStats($usageStatsRetention30m, $usageStatsRetention1d);
notifyDeleteConnections();
notifyDeleteExpiredSessions();
renewCertificates($database);
notifyDeleteCache($cacheRetention);
}, $interval);
});
+5 -30
View File
@@ -9,23 +9,12 @@ use Utopia\Cache\Cache;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\Text;
function clearProjectsCache(Redis $redis, Document $project)
{
try {
$redis->del($redis->keys("cache-_{$project->getInternalId()}:*"));
} catch (\Throwable $th) {
Console::error('Failed to clear project ("' . $project->getId() . '") cache with error: ' . $th->getMessage());
}
}
$cli
->task('migrate')
->param('version', APP_VERSION_STABLE, new Text(32), 'Version to migrate to.', true)
->param('version', APP_VERSION_STABLE, new Text(8), 'Version to migrate to.', true)
->action(function ($version) use ($register) {
Authorization::disable();
if (!array_key_exists($version, Migration::$versions)) {
@@ -40,7 +29,7 @@ $cli
$db = $register->get('db', true);
$redis = $register->get('cache', true);
$redis->flushAll();
$cache = new Cache(new RedisCache($redis));
$projectDB = new Database(new MariaDB($db), $cache);
@@ -55,9 +44,6 @@ $cli
$limit = 30;
$sum = 30;
$offset = 0;
/**
* @var \Utopia\Database\Document[] $projects
*/
$projects = [$console];
$count = 0;
@@ -73,30 +59,18 @@ $cli
while (!empty($projects)) {
foreach ($projects as $project) {
/**
* Skip user projects with id 'console'
*/
if ($project->getId() === 'console' && $project->getInternalId() !== 'console') {
continue;
}
clearProjectsCache($redis, $project);
try {
$migration
->setProject($project, $projectDB, $consoleDB)
->setPDO($register->get('db'))
->execute();
} catch (\Throwable $th) {
Console::error('Failed to update project ("' . $project->getId() . '") version with error: ' . $th->getMessage());
throw $th;
Console::error('Failed to update project ("' . $project->getId() . '") version with error: ' . $th->getMessage());
}
clearProjectsCache($redis, $project);
}
$sum = \count($projects);
$projects = $consoleDB->find('projects', [Query::limit($limit), Query::offset($offset)]);
$projects = $consoleDB->find('projects', limit: $limit, offset: $offset);
$offset = $offset + $limit;
$count = $count + $sum;
@@ -105,5 +79,6 @@ $cli
}
Swoole\Event::wait(); // Wait for Coroutines to finish
$redis->flushAll();
Console::success('Data Migration Completed');
});
+21 -39
View File
@@ -1,49 +1,42 @@
<?php
use Appwrite\SDK\Language\Android;
use Utopia\Config\Config;
use Utopia\CLI\Console;
use Appwrite\Spec\Swagger2;
use Appwrite\SDK\SDK;
use Appwrite\SDK\Language\CLI;
use Appwrite\SDK\Language\PHP;
use Appwrite\SDK\Language\Web;
use Appwrite\SDK\Language\Node;
use Appwrite\SDK\Language\Python;
use Appwrite\SDK\Language\Ruby;
use Appwrite\SDK\Language\Dart;
use Appwrite\SDK\Language\Deno;
use Appwrite\SDK\Language\DotNet;
use Appwrite\SDK\Language\Flutter;
use Appwrite\SDK\Language\Go;
use Appwrite\SDK\Language\GraphQL;
use Appwrite\SDK\Language\Kotlin;
use Appwrite\SDK\Language\Node;
use Appwrite\SDK\Language\PHP;
use Appwrite\SDK\Language\Python;
use Appwrite\SDK\Language\REST;
use Appwrite\SDK\Language\Ruby;
use Appwrite\SDK\Language\Android;
use Appwrite\SDK\Language\Swift;
use Appwrite\SDK\Language\Apple;
use Appwrite\SDK\Language\Web;
use Appwrite\SDK\SDK;
use Appwrite\Spec\Swagger2;
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Appwrite\SDK\Language\SwiftClient;
$cli
->task('sdks')
->action(function () {
$platforms = Config::getParam('platforms');
$selectedPlatform = Console::confirm('Choose Platform ("' . APP_PLATFORM_CLIENT . '", "' . APP_PLATFORM_SERVER . '", "' . APP_PLATFORM_CONSOLE . '" or "*" for all):');
$selectedSDK = \strtolower(Console::confirm('Choose SDK ("*" for all):'));
$selected = \strtolower(Console::confirm('Choose SDK ("*" for all):'));
$version = Console::confirm('Choose an Appwrite version');
$git = (Console::confirm('Should we use git push? (yes/no)') == 'yes');
$production = ($git) ? (Console::confirm('Type "Appwrite" to push code to production git repos') == 'Appwrite') : false;
$message = ($git) ? Console::confirm('Please enter your commit message:') : '';
if (!in_array($version, ['0.6.x', '0.7.x', '0.8.x', '0.9.x', '0.10.x', '0.11.x', '0.12.x', '0.13.x', '0.14.x', '0.15.x', '1.0.x', '1.1.x', '1.2.x', '1.3.x', 'latest'])) {
if (!in_array($version, ['0.6.x', '0.7.x', '0.8.x', '0.9.x', '0.10.x', '0.11.x', '0.12.x', '0.13.x', '0.14.x', '0.15.x', 'latest'])) {
throw new Exception('Unknown version given');
}
foreach ($platforms as $key => $platform) {
if ($selectedPlatform !== $key && $selectedPlatform !== '*') {
continue;
}
foreach ($platform['sdks'] as $language) {
if ($selectedSDK !== $language['key'] && $selectedSDK !== '*') {
foreach ($platform['languages'] as $language) {
if ($selected !== $language['key'] && $selected !== '*') {
continue;
}
@@ -79,20 +72,15 @@ Redistribution and use in source and binary forms, with or without modification,
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
3. Neither the name Appwrite nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.';
switch ($language['key']) {
case 'web':
$config = new Web();
if ($platform['key'] === APP_PLATFORM_CONSOLE) {
$config->setNPMPackage('@appwrite.io/console');
$config->setBowerPackage('@appwrite.io/console');
} else {
$config->setNPMPackage('appwrite');
$config->setBowerPackage('appwrite');
}
$config->setNPMPackage('appwrite');
$config->setBowerPackage('appwrite');
break;
case 'cli':
$config = new CLI();
@@ -160,7 +148,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
$warning = $warning . "\n\n > This is the Swift SDK for integrating with Appwrite from your Swift server-side code. If you're looking for the Apple SDK you should check [appwrite/sdk-for-apple](https://github.com/appwrite/sdk-for-apple)";
break;
case 'apple':
$config = new Apple();
$config = new SwiftClient();
break;
case 'dotnet':
$cover = '';
@@ -173,14 +161,9 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
$config = new Kotlin();
$warning = $warning . "\n\n > This is the Kotlin SDK for integrating with Appwrite from your Kotlin server-side code. If you're looking for the Android SDK you should check [appwrite/sdk-for-android](https://github.com/appwrite/sdk-for-android)";
break;
case 'graphql':
$config = new GraphQL();
break;
case 'rest':
$config = new REST();
break;
default:
throw new Exception('Language "' . $language['key'] . '" not supported');
break;
}
Console::info("Generating {$language['name']} SDK...");
@@ -195,7 +178,6 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
->setLicense($license)
->setLicenseContent($licenseContent)
->setVersion($language['version'])
->setPlatform($key)
->setGitURL($language['url'])
->setGitRepo($language['gitUrl'])
->setGitRepoName($language['gitRepoName'])
@@ -214,7 +196,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
->setTwitter(APP_SOCIAL_TWITTER_HANDLE)
->setDiscord(APP_SOCIAL_DISCORD_CHANNEL, APP_SOCIAL_DISCORD)
->setDefaultHeaders([
'X-Appwrite-Response-Format' => '1.0.0',
'X-Appwrite-Response-Format' => '0.15.0',
]);
try {
+1 -1
View File
@@ -16,7 +16,7 @@ use Utopia\Validator\WhiteList;
$cli
->task('specs')
->param('version', 'latest', new Text(16), 'Spec version', true)
->param('version', 'latest', new Text(8), 'Spec version', true)
->param('mode', 'normal', new WhiteList(['normal', 'mocks']), 'Spec Mode', true)
->action(function ($version, $mode) use ($register) {
$db = $register->get('db');
+38 -12
View File
@@ -2,23 +2,23 @@
global $cli, $register;
use Appwrite\Usage\Calculators\TimeSeries;
use Appwrite\Stats\Usage;
use Appwrite\Stats\UsageDB;
use InfluxDB\Database as InfluxDatabase;
use Utopia\App;
use Utopia\Cache\Adapter\Redis as RedisCache;
use Utopia\Cache\Cache;
use Utopia\CLI\Console;
use Utopia\Database\Adapter\MariaDB;
use Utopia\Database\Database as UtopiaDatabase;
use Utopia\Database\Database;
use Utopia\Database\Validator\Authorization;
use Utopia\Registry\Registry;
use Utopia\Logger\Log;
use Utopia\Validator\WhiteList;
Authorization::disable();
Authorization::setDefaultStatus(false);
function getDatabase(Registry &$register, string $namespace): UtopiaDatabase
function getDatabase(Registry &$register, string $namespace): Database
{
$attempts = 0;
@@ -30,7 +30,7 @@ function getDatabase(Registry &$register, string $namespace): UtopiaDatabase
$redis = $register->get('cache');
$cache = new Cache(new RedisCache($redis));
$database = new UtopiaDatabase(new MariaDB($db), $cache);
$database = new Database(new MariaDB($db), $cache);
$database->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite'));
$database->setNamespace($namespace);
@@ -38,7 +38,7 @@ function getDatabase(Registry &$register, string $namespace): UtopiaDatabase
throw new Exception('Projects collection not ready');
}
break; // leave loop if successful
} catch (\Exception $e) {
} catch (\Exception$e) {
Console::warning("Database not ready. Retrying connection ({$attempts})...");
if ($attempts >= DATABASE_RECONNECT_MAX_ATTEMPTS) {
throw new \Exception('Failed to connect to database: ' . $e->getMessage());
@@ -65,7 +65,7 @@ function getInfluxDB(Registry &$register): InfluxDatabase
if (in_array('telegraf', $client->listDatabases())) {
break; // leave the do-while if successful
}
} catch (\Throwable $th) {
} catch (\Throwable$th) {
Console::warning("InfluxDB not ready. Retrying connection ({$attempts})...");
if ($attempts >= $max) {
throw new \Exception('InfluxDB database not ready yet');
@@ -117,22 +117,48 @@ $cli
Console::title('Usage Aggregation V1');
Console::success(APP_NAME . ' usage aggregation process v1 has started');
$interval = (int) App::getEnv('_APP_USAGE_AGGREGATION_INTERVAL', '30'); // 30 seconds (by default)
$database = getDatabase($register, '_console');
$influxDB = getInfluxDB($register);
$interval = (int) App::getEnv('_APP_USAGE_AGGREGATION_INTERVAL', '30'); // 30 seconds (by default)
$region = App::getEnv('region', 'default');
$usage = new TimeSeries($region, $database, $influxDB, $logError);
$usage = new Usage($database, $influxDB, $logError);
$usageDB = new UsageDB($database, $logError);
Console::loop(function () use ($interval, $usage) {
$iterations = 0;
Console::loop(function () use ($interval, $usage, $usageDB, &$iterations) {
$now = date('d-m-Y H:i:s', time());
Console::info("[{$now}] Aggregating Timeseries Usage data every {$interval} seconds");
Console::info("[{$now}] Aggregating usage data every {$interval} seconds");
$loopStart = microtime(true);
/**
* Aggregate InfluxDB every 30 seconds
*/
$usage->collect();
if ($iterations % 30 != 0) { // return if 30 iterations has not passed
$iterations++;
$loopTook = microtime(true) - $loopStart;
$now = date('d-m-Y H:i:s', time());
Console::info("[{$now}] Aggregation took {$loopTook} seconds");
return;
}
$iterations = 0; // Reset iterations to prevent overflow when running for long time
/**
* Aggregate MariaDB every 15 minutes
* Some of the queries here might contain full-table scans.
*/
$now = date('d-m-Y H:i:s', time());
Console::info("[{$now}] Aggregating database counters.");
$usageDB->collect();
$iterations++;
$loopTook = microtime(true) - $loopStart;
$now = date('d-m-Y H:i:s', time());
Console::info("[{$now}] Aggregation took {$loopTook} seconds");
}, $interval);
});
+368
View File
@@ -0,0 +1,368 @@
<div class="cover">
<h1 class="zone xl margin-bottom-large">
<a data-ls-attrs="href=/console" class="back text-size-small link-return-animation--start"><i class="icon-left-open"></i> Home</a>
<br />
<span>Your Account</span>
</h1>
</div>
<div class="zone xl">
<ul class="phases clear" data-ui-phases data-selected="{{router.params.tab}}">
<li data-state="/console/account">
<h2 class="margin-bottom">Overview</h2>
<div
data-service="account.get"
data-scope="console"
data-name="account"
data-event="load"
data-failure="trigger"
data-failure-param-trigger-events="account.deleteSession">
<div class="row responsive force-reverse">
<div class="col span-3 text-align-center margin-bottom">
<img src="" data-ls-attrs="src={{account|avatar}}" data-size="200" height="150" alt="User Avatar" class="avatar huge huge margin-bottom-small" />
</div>
<div class="col span-9">
<div class="box margin-bottom-xl">
<div>
<form name="account.update"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Update Account Name"
data-service="account.updateName"
data-scope="console"
data-event="submit"
data-success="trigger,alert"
data-success-param-alert-text="Your name was updated successfully"
data-success-param-trigger-events="account.update"
data-failure="alert"
data-failure-param-alert-text="Failed to update your name"
data-failure-param-alert-classname="error">
<label for="name">Name</label>
<div class="row responsive">
<div class="col span-8 margin-bottom-small">
<input name="name" id="name" type="text" autocomplete="off" data-ls-bind="{{account.name}}" required class="margin-bottom-no" maxlength="128">
</div>
<div class="col span-4">
<button type="submit" class="fill margin-bottom-no">Update Name</button>
</div>
</div>
</form>
</div>
<hr />
<form name="update-email"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Update Account Email"
data-service="account.updateEmail"
data-scope="console"
data-event="submit"
data-success="trigger,alert"
data-success-param-alert-text="Email address updated successfully"
data-success-param-trigger-events="account-update,modal-close"
data-failure="alert"
data-failure-param-alert-text="Failed updating email address"
data-failure-param-alert-classname="error">
<label>Email</label>
<div class="row responsive">
<div class="col span-8 margin-bottom-small">
<input name="email" type="email" class="margin-bottom-no" autocomplete="off" placeholder="me@example.com" data-ls-bind="{{account.email}}" required>
</div>
<div class="col span-4">
<div data-ui-modal class="modal box close width-small height-small" data-button-text="Update Email" data-button-class="fill">
<h3>Confirm Password</h3>
<hr />
<label>Password</label>
<input name="password" type="password" class="full-width" autocomplete="off" placeholder="" required>
<hr />
<button type="submit" class="margin-bottom-no">Update</button> &nbsp; <button data-ui-modal-close="" type="button" class="reverse">Cancel</button>
</div>
</div>
</div>
</form>
<hr />
<div data-ui-modal class="modal box close width-small" data-button-text="Update Password" data-button-class="">
<h1>Update Password</h1>
<form name="update-password"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Update Account Password"
data-service="account.updatePassword"
data-scope="console"
data-event="submit"
data-success="trigger,alert,reset"
data-success-param-trigger-events="account-update"
data-success-param-alert-text="Password updated successfully"
data-failure="alert"
data-failure-param-alert-text="Failed updating password"
data-failure-param-alert-classname="error">
<label>Current Password</label>
<input name="oldPassword" type="password" class="full-width" autocomplete="off" placeholder="" required>
<label>New Password</label>
<input name="password" type="password" class="full-width" autocomplete="off" placeholder="" required data-forms-password-meter>
<hr />
<footer>
<button type="submit">Update Password</button> &nbsp; <button data-ui-modal-close="" type="button" class="reverse">Cancel</button>
</footer>
</form>
</div>
<hr />
<form class="margin-top"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Delete Account Current Session"
data-service="account.deleteSession"
data-scope="console"
data-event="submit"
data-success="trigger"
data-success-param-trigger-events="account.deleteSession"
data-failure="alert"
data-failure-param-alert-text="Logout failed"
data-failure-param-alert-classname="error">
<input type="hidden" name="sessionId" value="current">
<button class="fill danger icon fill"><i class="icon-login"></i> Logout</button>
</form>
</div>
</div>
</div>
<div class="row responsive">
<div class="col span-9">
<h3 class="text-danger">Danger Zone</h3>
<div class="box danger">
<p>This is the area where you can delete your account.</p>
<p>By deleting your account you will lose access to any of your teams and shared data.</p>
<p>PLEASE NOTE: Account deletion is irreversible.</p>
<form class="inline"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Delete Account"
data-service="account.delete"
data-scope="console"
data-event="submit"
data-confirm="Are you sure you want to delete your account?"
data-success="trigger"
data-success-param-trigger-events="account.delete"
data-failure="alert"
data-failure-param-alert-text="Account deactivation failed"
data-failure-param-alert-classname="error">
<button class="danger reverse">Delete Account</button>
</form>
</div>
</div>
<div class="col span-3"></div>
</div>
</div>
</li>
<li data-state="/console/account/sessions">
<h2>Sessions</h2>
<div class="box margin-bottom"
data-service="account.getSessions"
data-scope="console"
data-name="sessions"
data-event="load,account.deleteRemoteSession">
<ul data-ls-loop="sessions.sessions" data-ls-as="session" class="list">
<li class="clear">
<span data-ls-if="true != {{session.current}}">
<!-- From remote session (-logout event) -->
<form class="pull-end"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Delete Account Session"
data-service="account.deleteSession"
data-scope="console"
data-event="submit"
data-loading="Loading..."
data-success="trigger"
data-success-param-trigger-events="account.deleteRemoteSession"
data-failure="alert"
data-failure-param-alert-text="Logout from Session Failed"
data-failure-param-alert-classname="error">
<input type="hidden" name="sessionId" data-ls-bind="{{session.$id}}">
<button class="danger">Logout</button>
</form>
</span>
<span data-ls-if="true == {{session.current}}">
<!-- From current session (+logout event) -->
<form class="pull-end"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Delete Account Current Session"
data-service="account.deleteSession"
data-scope="console"
data-event="submit"
data-loading="Loading..."
data-success="trigger,redirect"
data-success-param-trigger-events="account.deleteSession"
data-success-param-redirect-url="/"
data-failure="alert"
data-failure-param-alert-text="Logout from Session Failed"
data-failure-param-alert-classname="error">
<input type="hidden" name="sessionId" data-ls-bind="{{session.$id}}">
<button class="danger">Logout</button>
</form>
</span>
<div class="pull-start margin-end avatar-container">
<img onerror="this.onerror=null;this.className='avatar hide'" data-ls-attrs="src={{env.API}}/avatars/browsers/{{session.clientCode|lowercase}}?width=120&height=120&project={{env.PROJECT}},title={{session.clientName}},alt={{session.clientName}}" class="avatar" loading="lazy" width="60" height="60" data-ls-if="{{session.clientCode|lowercase}} !== 'cli'"/>
<img onerror="this.onerror=null;this.className='avatar hide'" data-ls-attrs="src=/images/clients/terminal.png?buster=<?php echo APP_CACHE_BUSTER; ?>,title={{session.clientName}},alt={{session.clientName}}" class="avatar" loading="lazy" width="60" height="60" data-ls-if="{{session.clientCode|lowercase}} === 'cli'" >
<div data-ls-if="{{session.provider}} !== 'email'" class="corner">
<img data-ls-attrs="src=/images/users/{{session.provider}}.png?buster=<?php echo APP_CACHE_BUSTER; ?>,title={{session.provider}},alt={{session.provider}}" class="avatar xs" loading="lazy" width="30" height="30" />
</div>
</div>
<span data-ls-if="(!{{log.clientName}})">Unknown</span>
<span data-ls-if="({{log.clientName}})" data-ls-bind="{{session.clientName}}"></span> <span data-ls-bind="{{session.clientVersion}}"></span> on <span data-ls-bind="{{session.deviceModel}}"></span> <span data-ls-bind="{{session.osName}}"></span> <span data-ls-bind="{{session.osVersion}}"></span>
&nbsp;
<span data-ls-if="true == {{session.current}}">
<span class="tag green">Current Session</span>
</span>
<div class="margin-top-small">
<img onerror="this.onerror=null;this.className='avatar hide'" data-ls-if="{{session.countryCode}} !== '--'" data-ls-attrs="src={{env.API}}/avatars/flags/{{session.countryCode}}?width=80&height=80&project={{env.PROJECT}}" class="avatar xxs margin-end-small inline" />
<small data-ls-bind="{{session.ip}}"></small> / <small data-ls-bind="{{session.countryName}}"></small>
</div>
</li>
</ul>
</div>
<form class="inline margin-bottom-large"
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Delete Account Sessions"
data-service="account.deleteSessions"
data-scope="console"
data-event="submit"
data-success="trigger,redirect"
data-success-param-trigger-events="account.deleteSession"
data-success-param-redirect-url="/"
data-failure="alert"
data-failure-param-alert-text="Logout from All Sessions Failed"
data-failure-param-alert-classname="error">
<input type="hidden" name="id" value="0">
<button class="danger">Logout from all sessions</button>
</form>
</li>
<li data-state="/console/account/activity">
<h2>Activity</h2>
<div
data-service="account.getLogs"
data-scope="console"
data-name="securityLogs"
data-event="load">
<div class="box margin-bottom">
<table class="vertical small">
<thead>
<tr>
<th width="120">Date</th>
<th width="175">Event</th>
<th>Client</th>
<th width="110">Location</th>
<th width="90">IP</th>
</tr>
</thead>
<tbody data-ls-loop="securityLogs.logs" data-ls-as="log">
<tr>
<td data-title="Date: "><span data-ls-bind="{{log.time|dateTime}}"></span></td>
<td data-title="Event: "><span data-ls-bind="{{log.event}}"></span></td>
<td data-title="Client: ">
<img onerror="this.onerror=null;this.className='avatar hide'" data-ls-attrs="src={{env.API}}/avatars/browsers/{{log.clientCode|lowercase}}?width=80&height=80&project={{env.PROJECT}},title={{log.clientName}},alt={{log.clientName}}" class="avatar xxs inline margin-end-small" data-ls-if="{{log.clientCode|lowercase}} !== 'cli'"/>
<img onerror="this.onerror=null;this.className='avatar hide'" data-ls-attrs="src=/images/clients/terminal.png?buster=<?php echo APP_CACHE_BUSTER; ?>,title={{log.clientName}},alt={{log.clientName}}" class="avatar xxs inline margin-end-small" data-ls-if="{{log.clientCode|lowercase}} === 'cli'" />
<span data-ls-if="(!{{log.clientName}})">Unknown</span>
<span data-ls-if="({{log.clientName}})" data-ls-bind="{{log.clientName}} {{log.clientVersion}} on {{log.model}} {{log.osName}} {{log.osVersion}}"></span>
</td>
<td data-title="Location: ">
<img onerror="this.onerror=null;this.className='avatar xxs hide'" data-ls-attrs="src={{env.API}}/avatars/flags/{{log.countryCode}}?width=80&height=80&project={{env.PROJECT}}" class="avatar xxs inline margin-end-small" />
<span data-ls-bind="{{log.countryName}}"></span>
</td>
<td data-title="IP: "><span data-ls-bind="{{log.ip}}"></span></td>
</tr>
</tbody>
</table>
</div>
<div class="pull-end text-align-center paging">
<form
data-service="account.getLogs"
data-event="submit"
data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
data-param-offset="{{router.params.offset}}"
data-scope="console"
data-name="securityLogs"
data-success="state"
data-success-param-state-keys="offset">
<button name="offset" data-paging-back data-offset="{{router.params.offset}}" data-total="{{securityLogs.total}}" class="margin-end round small" aria-label="Back"><i class="icon-left-open"></i></button>
</form>
<span data-ls-bind="{{router.params.offset|pageCurrent}} / {{securityLogs.total|pageTotal}}"></span>
<form
data-service="account.getLogs"
data-event="submit"
data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
data-param-offset="{{router.params.offset}}"
data-scope="console"
data-name="securityLogs"
data-success="state"
data-success-param-state-keys="offset">
<button name="offset" data-paging-next data-offset="{{router.params.offset}}" data-total="{{securityLogs.total}}" class="margin-start round small" aria-label="Next"><i class="icon-right-open"></i></button>
</form>
</div>
</div>
</li>
</ul>
</div>
+43
View File
@@ -0,0 +1,43 @@
<?php
$home = $this->getParam('home', '');
$version = $this->getParam('version', '') . '.' . APP_CACHE_BUSTER;
?>
<footer class="clear margin-top-large">
<ul class="copyright pull-start">
<li>
<a class="link-animation-enabled"
data-analytics
data-analytics-event="click"
data-analytics-category="console/footer"
data-analytics-label="GitHub Link"
href="https://github.com/appwrite/appwrite" target="_blank" rel="noopener"><i class="icon-github"></i> GitHub</a>
</li>
<li>
<a class="link-animation-enabled"
data-analytics
data-analytics-event="click"
data-analytics-category="console/footer"
data-analytics-label="Discord Link"
href="https://appwrite.io/discord" target="_blank" rel="noopener"><i class="icon-discord"></i> Discord</a>
</li>
<li>
<a class="link-animation-enabled"
data-analytics
data-analytics-event="click"
data-analytics-category="console/footer"
data-analytics-label="New GitHub Issue"
href="https://github.com/appwrite/appwrite/issues/new?assignees=&labels=bug&template=bug.yaml&title=[<?php echo $version; ?>]%20%F0%9F%90%9B+Bug+Report%3A+" target="_blank" rel="noopener">Open an Issue</a>
</li>
<li>
<a class="link-animation-enabled"
data-analytics
data-analytics-event="click"
data-analytics-category="console/footer"
data-analytics-label="Docs Link"
href="<?php echo $home; ?>/docs" target="_blank" rel="noopener">Docs</a>
</li>
<li>
v:<?php echo $version; ?>
</li>
</ul>
</footer>
+259
View File
@@ -0,0 +1,259 @@
<header class="clear" data-version>
<a href="/console" class="logo pull-start">
<img src="/images/appwrite.svg" alt="Appwrite Light Logo" class="force-light" loading="lazy" />
<img src="/images/appwrite-footer-dark.svg" alt="Appwrite Dark Logo" class="force-dark" loading="lazy" />
</a>
<div class="change-project pull-start desktops-only">
<div class="list project-only margin-end-small">
<label class="margin-bottom-no">
<select class="margin-bottom-no"
data-xanalytics-event="change"
data-xanalytics-category="console/header"
data-xanalytics-label="Project Switch"
data-switch
data-ls-bind="{{router.params.project}}"
data-unsync="1"
data-ls-loop="projects.projects" data-ls-as="option" aria-label="Switch Project">
<option data-ls-attrs="value={{option.$id}}" data-ls-bind="{{option.name}}"></option>
</select>
</label>
</div>
<button style="overflow: visible;" class="project-only setup-new tooltip round down pull-end" aria-label="Quick Start" data-tooltip="Create a new project"><i class="icon-plus"></i></button>
</div>
<div class="account-box pull-end"
data-service="account.get"
data-name="account"
data-scope="console"
data-event="load"
data-success="trigger"
data-success-param-trigger-events="account.get"
data-failure="trigger"
data-failure-param-trigger-events="account.deleteSession">
<div class="console-back">
<a href="/console" class="link-return-animation--end">Back to Console &nbsp;<i class="icon-right-open"></i></a>
</div>
<div class="account link pull-end clear">
<img src="" data-ls-attrs="src={{account|avatar}}" alt="User Avatar" class="avatar margin-start pull-end" />
<span class="name pull-end desktops-only" data-ls-bind="{{account.name}}"></span>
</div>
<div class="console-index drop-list bottom end" data-ls-ui-open="" data-button-text="" data-button-aria="Account Options" data-button-icon="" data-button-selector="[data-toggler]" data-button-class="account-button" data-blur="1">
<ul class="margin-top-large arrow-end">
<li>
<a href="/console/account"><i class="icon-user"></i> &nbsp; Your Account</a>
</li>
<li>
<span class="link"><i class="icon-sun-inv force-dark pull-start"></i><i class="icon-moon-inv force-light pull-start"></i> &nbsp; Change Theme
<div class="pull-end switch-theme">
<button data-general-theme
data-analytics
data-analytics-event="click"
data-analytics-category="console/header"
data-analytics-label="Switch Theme">
<i class="icon-sun-inv force-light"></i>
<i class="icon-moon-inv force-dark"></i>
</button>
</div>
</span>
</li>
</ul>
</div>
</div>
<nav class="project-only" data-ls-ui-open="" data-button-class="round icon-btn phones-only tablets-only" data-button-aria="Navigation" data-button-icon="icon-dot-3">
<a class="logo" href="/console"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Logo Link">
<img src="/images/appwrite-nav.svg" loading="lazy" alt="Appwrite Logo" class="nav" />
<img src="/images/appwrite.svg" loading="lazy" alt="Appwrite Light Logo" class="top force-light" loading="lazy" />
<img src="/images/appwrite-footer-dark.svg" loading="lazy" alt="Appwrite Dark Logo" class="top force-dark" loading="lazy" />
</a>
<div data-ui-highlight class="container">
<ul class="links">
<li>
<a data-ls-attrs="href=/console/home?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Home Link">
<i class="icon-home"></i>
Home
</a>
</li>
</ul>
<b class="subtitle">DEVELOP</b>
<ul class="links">
<li>
<a data-ls-attrs="href=/console/databases?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Database Link">
<i class="icon-database"></i>
Database
</a>
</li>
<li>
<a data-ls-attrs="href=/console/storage?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Storage Link">
<i class="icon-folder"></i>
Storage
</a>
</li>
<li>
<a data-ls-attrs="href=/console/users?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Users Link">
<i class="icon-users"></i>
Users
</a>
</li>
<li>
<a data-ls-attrs="href=/console/functions?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Functions Link"
class="link-animation-disabled">
<i class="icon-lightning"></i>
Functions
</a>
</li>
</ul>
<b class="subtitle">MANAGE</b>
<ul class="links">
<li>
<a data-ls-attrs="href=/console/webhooks?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Webhooks Links">
<i class="icon-link"></i>
Webhooks
</a>
</li>
<li>
<a data-ls-attrs="href=/console/keys?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="API Keys Link">
<i class="icon-key-inv"></i>
API Keys
</a>
</li>
</ul>
</div>
<ul class="links bottom">
<li>
<a data-ls-attrs="href=/console/settings?project={{router.params.project}}"
data-analytics
data-analytics-event="click"
data-analytics-category="console/navigation"
data-analytics-label="Settings Link">
<i class="icon-cog"></i> Settings</a>
</li>
</ul>
</nav>
</header>
<div class=""
data-service="projects.list"
data-event="load,projects.update"
data-name="projects"
data-scope="console"></div>
<div class="load-screen" data-ls-ui-loader>
<div class="animation"><div></div><div></div><div></div><div></div></div>
<img src="/images/appwrite.svg" alt="Appwrite Light Logo" class="force-light" loading="lazy" />
<img src="/images/appwrite-footer-dark.svg" alt="Appwrite Dark Logo" class="force-dark" loading="lazy" />
</div>
<div data-ui-modal class="modal box close sticky-footer" data-button-alias=".setup-new" data-button-icon="icon-plus" data-button-class="project-only" data-open-event="create-project">
<h1>Create Project</h1>
<form
data-setup
data-analytics
data-analytics-activity
data-analytics-event="submit"
data-analytics-category="console"
data-analytics-label="Create Project">
<p>Appwrite projects are containers for your resources and apps across different platforms.</p>
<label>Project ID</label>
<input
type="hidden"
data-custom-id
data-id-type="auto"
data-validator="projects.get"
required
maxlength="36"
class=""
pattern="^[a-zA-Z0-9][a-zA-Z0-9._-]{0,35}$"
name="projectId" />
<label>Name</label>
<input type="text" class="full-width margin-bottom-xl" name="name" required autocomplete="off" maxlength="128" />
<footer>
<button type="submit">Create</button> &nbsp; <button data-ui-modal-close="" type="button" class="reverse">Cancel</button>
</footer>
</form>
</div>
<section class="upload-box" x-data x-show="$store.uploader.files().length > 0">
<div class="upload-box-header">
<h4 class="upload-box-title">
<span class="text">Uploading files</span>
<span class="amount" x-text="$store.uploader.files().length"></span>
</h4>
<button class="icon-button" :class="$store.uploader.isOpen ? '' : 'is-open'" aria-label="toggle upload box" @click="$store.uploader.toggle()"><span class="icon-chevron-down" aria-hidden="true"></span></button>
<button class="icon-button" @click="$store.uploader.cancelAll()" aria-label="close upload box"><span class="icon-x" aria-hidden="true"></span></button>
</div>
<div class="upload-box-content" :class="$store.uploader.isOpen ? 'is-open' : ''">
<ul class="upload-box-list">
<template x-if="$store.uploader.files().length > 0">
<template x-for="file in $store.uploader.files()" :key="file.id">
<li x-show="!file.cancelled" class="upload-box-item">
<div class="upload-image u-margin-inline-end-16" :class="file.completed ? 'is-finished' : ''">
<div class="progress"
:style="'--progress-value:' + file.progress"
:aria-valuenow="file.progress"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"></div>
<span x-show="!file.completed" class="icon" x-text="file.progress + '%'"></span>
<span x-show="file.completed" class="icon icon-file"></span>
</div>
<label for="file1" class="file-name trim-inner-text" x-text="file.name" :title="file.name"></label>
<span class="pill is-failed" x-show="file.failed" :title="file.error">failed</span>
<button x-show="file.completed" class="icon-button is-success" aria-label="Uploading"><span class="icon-check"></span></button>
<button x-show="!file.completed" class="icon-button" aria-label="Uploading" @click="$store.uploader.removeFile(file.id)"><span class="icon-x"></span></button>
</li>
</template>
</template>
</ul>
</div>
</section>
+96
View File
@@ -0,0 +1,96 @@
<?php
$interval = floor((int)$this->getParam('interval', 0) / 86400);
$method = $this->getParam('method', '');
$params = $this->getParam('params', []);
?>
<div
data-service="<?php echo $method; ?>"
<?php foreach($params as $key => $value): ?>
data-param-<?php echo $key; ?>="<?php echo $value; ?>"
<?php endforeach; ?>
data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
data-scope="sdk"
data-event="load"
data-name="logs">
<div data-ls-if="0 == {{logs.logs.length}}">
<div class="box margin-bottom">
<h3 class="margin-bottom-small text-bold">No Logs Found</h3>
<p class="margin-bottom-no">Logs are retained for <?php echo $this->escape($interval); ?> days.</p>
</div>
</div>
<div data-ls-if="0 != {{logs.total}}">
<div class="margin-bottom-small margin-top-negative text-align-end text-size-small text-fade">Showing logs from the last <?php echo $this->escape($interval); ?> days</div>
<div class="box margin-bottom">
<table class="vertical small">
<thead>
<tr>
<th width="120">Date</th>
<th width="180">By</th>
<th>Event</th>
<th width="110">Location</th>
<th width="90">IP</th>
</tr>
</thead>
<tbody data-ls-loop="logs.logs" data-ls-as="log" class="text-size-small">
<tr>
<td data-title="Date: "><span class="text-fade" data-ls-bind="{{log.time|dateTime}}"></span></td>
<td data-title="By: ">
<span data-ls-if="{{log.userName|escape}} !== '' && {{log.mode}} === ''"><i class="icon-user"></i>&nbsp; <a data-ls-attrs="href=/console/users/user?id={{log.userId}}&project={{router.params.project}}" data-ls-bind="{{log.userName}}"></a></span>
<span data-ls-if="{{log.userName|escape}} === '' && {{log.userEmail}} !== '' && {{log.mode}} !== 'key'"><i class="icon-user"></i>&nbsp; Unknown</span>
<span data-ls-if="{{log.userName|escape}} === '' && {{log.userEmail}} === '' && {{log.mode}} !== 'key'"><i class="icon-user"></i>&nbsp; Anonymous User</span>
<span data-ls-if="{{log.mode}} === 'admin'">
<img src="" data-ls-attrs="src={{log.userName|avatar}}" data-size="45" alt="User Avatar" class="avatar xxs inline margin-end-small" loading="lazy" width="30" height="30" /> <span data-ls-bind="{{log.userName}}"></span> <span class="text-fade text-size-xs">(Admin)</span>
</span>
<span data-ls-if="{{log.mode}} === 'key'"> <i class="icon-key"></i>&nbsp; API Key</span>
</td>
<td data-title="Event: "><span data-ls-bind="{{log.event}}"></span></td>
<td data-title="Location: ">
<img onerror="this.onerror=null;this.className='avatar xxs hide'" data-ls-attrs="src={{env.API}}/avatars/flags/{{log.countryCode}}?width=80&height=80&project={{env.PROJECT}}" class="avatar xxs inline margin-end-small" />
<span data-ls-bind="{{log.countryName}}"></span>
</td>
<td data-title="IP: "><span data-ls-bind="{{log.ip}}"></span></td>
</tr>
</tbody>
</table>
</div>
<div class="pull-end text-align-center paging">
<form
data-service="<?php echo $method; ?>"
<?php foreach($params as $key => $value): ?>
data-param-<?php echo $key; ?>="<?php echo $value; ?>"
<?php endforeach; ?>
data-event="submit"
data-param-collection-id="{{router.params.id}}"
data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
data-param-order-type="DESC"
data-scope="sdk"
data-name="logs"
data-success="state"
data-success-param-state-keys="search,offset">
<button name="offset" data-paging-back data-offset="{{router.params.offset}}" data-total="{{logs.total}}" class="margin-end-small round small" aria-label="Back"><i class="icon-left-open"></i></button>
</form>
<span data-ls-bind="{{router.params.offset|pageCurrent}} / {{logs.total|pageTotal}}"></span>
<form
data-service="<?php echo $method; ?>"
<?php foreach($params as $key => $value): ?>
data-param-<?php echo $key; ?>="<?php echo $value; ?>"
<?php endforeach; ?>
data-event="submit"
data-param-collection-id="{{router.params.id}}"
data-param-limit="<?php echo APP_PAGING_LIMIT; ?>"
data-param-order-type="DESC"
data-scope="sdk"
data-name="logs"
data-success="state"
data-success-param-state-keys="search,offset">
<button name="offset" data-paging-next data-offset="{{router.params.offset}}" data-total="{{logs.total}}" class="margin-start-small round small" aria-label="Next"><i class="icon-right-open"></i></button>
</form>
</div>
</div>
</div>
@@ -0,0 +1,6 @@
<div x-data id="upload-modal">
<template x-for="$store.uploader.files as file">
<p x-text="file"></p>
</template>
<button @click="$store.uploader.addFile('file-x')">add</button>
</div>

Some files were not shown because too many files have changed in this diff Show More